使用LINQ,获取满足分组标准的项目数

Mat*_*att 9 .net c# linq

如果我努力的话,我可能会去修理术语,所以通过代码描述它会更容易:

var fooGroup = fooList.GroupBy(x => x.SomeID);
//fooGroup is now of type IEnumerable<IGrouping<int, Foo>>
var someCount = fooGroup.Count(y => y.Where(f => f.Bar == "Bar"));

由于此错误,上述内容将无法编译:"无法将lambda表达式转换为委托类型,System.Func<System.Linq.IGrouping<int,Foo>,bool> 因为块中的某些返回类型不能隐式转换为委托返回类型"

我认为答案很简单,但我不能完全理解如何做到这一点.

Kha*_*han 10

你想要对一个小组做什么并不是很有意义.我提出以下建议.

如果您正在寻找有多少元素Bar == "Bar",那么在该组之前进行.

var someCount = fooList.Count(y => f.Bar == "Bar");
Run Code Online (Sandbox Code Playgroud)

如果您要计算包含符合相同条件的元素的组.

var fooGroup = fooList.GroupBy(x => x.SomeID)
    .Where(x => x.Any(z => z.Bar == "Bar")).Count();
Run Code Online (Sandbox Code Playgroud)


h.a*_*lex 6

IEnumerable<IGrouping<int, Foo>>你进行分组.

这是一个IEnumerable群体.该组具有密钥类型int,这是因为您按int id列分组.分组包含一个IEnumerable包含所有具有此密钥的对象列表.它是类型Foo.

那么这是一个简单的查询.从分组中,您可以找到具有所需密钥的那些(即int id),然后从组中选择计数IEnumerable.

var fooGrouping = fooList.GroupBy(x => x.SomeID);
var someCount = fooGrouping.Where(grp => grp.Key == someKey).Select(p=>p.Count());
Run Code Online (Sandbox Code Playgroud)