Group by,Count和Lambda Expression

我正在尝试翻译以下查询:

SELECT STATE, COUNT(*) FROM MYTABLE GROUP BY STATE; 

进入lambda表达式。 我正在使用C#和EntityFramework,但似乎我无法使其工作。 到目前为止,这是我在我的存储库中的内容:

 public IEnumerable PorcentajeState(Guid id) { return _context.Sates.Where(a => a.Id == id) .GroupBy(a => a.State) .Select(n => new { n.StateId , n.Count() }); } 

当然它没有编译,我在谷歌搜索2小时后迷路了。 请你帮助我好吗?

提前致谢

这里有两个问题:

  1. GroupBy的结果将是IEnumerable>类型的可枚举。 IGrouping接口只有一个您可以访问的属性, Key是您在GroupBy表达式中指定的键,并实现IEnumerable因此您可以对结果执行其他Linq操作。
  2. 如果无法从属性或字段表达式推断出匿名类型,则需要为匿名类型指定属性名称。 在这种情况下,您在IGrouping上调用Count ,因此您需要为该属性指定名称。

试试这个:

 public IEnumerable PorcentajeState(Guid id) { return _context.Sates.Where(a => a.Id == id) .GroupBy(a => a.StateId) .Select(g => new { g.Key, Count = g.Count() }); } 

查询语法中的等价物将是

 public IEnumerable PorcentajeState(Guid id) { return from a in _context.Sates where a.Id == id group a by a.StateId into g select new { a.Key, Count = g.Count() }; } 

在任何一种情况下,如果您希望将第一个属性命名为StateId而不是Key ,则只需将其更改为

 new { StateId = g.Key, Count = g.Count() } 

这个很好

 public IEnumerable PorcentajeState(Guid id) { return _context.Sates.Where(a => a.Id == id) .GroupBy(a => a.StateId) .Select(g => new { g.Key, Count = g.Count() }); } 

但试试这个。

 public IEnumerable PorcentajeState(Guid id) { return _context.Sates.Where(a => a.Id == id) .GroupBy(a => a.StateId) .Select(g => new { g.Key.StateId, Count = g.Count() }); }