集团由伯爵和Lambda表达式 [英] Group by, Count and Lambda Expression

查看:141
本文介绍了集团由伯爵和Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想翻译下面的查询:

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



进入一个lambda表达式。我使用C#和的EntityFramework,但它似乎没有我可以使它发挥作用。以下是我对我的程序存储库至今:

Into a lambda expression. I am using C# and EntityFramework, however it doesnt seem I can make it work. Here is what I have on my respository so far:

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



当然它不编译,我google搜索2小时后消失。你能帮我吗?

Of course it doesnt compile and I am lost after googling for 2 hours . Could you please help me?

在此先感谢

推荐答案

有有两个问题在这里:


  1. GROUPBY 将将是一个枚举类型的的IEnumerable< IGrouping< TKEY的,TSource> ;> 。该 IGrouping 接口只有一个属性您可以访问,这是您在 GROUPBY 表达指定的键,并实施 IEnumerable的< T> 这样你就可以对结果做其他的LINQ操作。

  2. 您需要为匿名类型指定属性的名称,如果它不能从属性或字段表达推断。在这种情况下,你调用计数 IGrouping ,所以你需要该属性指定一个名称。

  1. The result of GroupBy will will be an enumerable of type IEnumerable<IGrouping<TKey, TSource>>. The IGrouping interface only has one property you can access, Key which is the key you specified in the GroupBy expression, and implements IEnumerable<T> so you can do other Linq operations on the result.
  2. You need to specify a property name for the anonymous type if it cannot be inferred from a property or field expression. In this case, you're calling Count on the IGrouping, so you need to specify a name for that property.

试试这个:

public IEnumerable<object> 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<object> 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() };
}

在这两种情况下,如果你想被命名为<$ c中的第一个属性$ C> STATEID 而不是,只更改为

In either case, if you want the first property to be named StateId instead of Key, just change that to

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

这篇关于集团由伯爵和Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆