如何访问 linq 查询返回的分组值
我有以下代码:
List<Person> people = new List<Person>
{
new Person{ Id = 1, Name = "Bob"},
new Person{ Id = 2, Name = "Joe"},
new Person{ Id = 3, Name = "Bob"}
};
var peopleGroupedByName = from p in people
group p by p.Name;
//get all groups where the number of people in the group is > 1
对于我的一生,我无法弄清楚如何使用 linq 查询返回的值,以便能够过滤返回的所有组,以便我只拥有这些组其中包含不止一件物品。
目前,我正在用头撞墙,我不太想出在谷歌搜索中使用哪些关键字才能自己找到答案。
我真的很感谢任何有关如何在 Linq 中执行此操作的帮助,因为看起来应该非常简单。
I've got the following code:
List<Person> people = new List<Person>
{
new Person{ Id = 1, Name = "Bob"},
new Person{ Id = 2, Name = "Joe"},
new Person{ Id = 3, Name = "Bob"}
};
var peopleGroupedByName = from p in people
group p by p.Name;
//get all groups where the number of people in the group is > 1
For the life of me I can't figure out how to work with the values returned by the linq query to be able to then filter all of the groups that were returned so that I only have the groups that have more than one item in them.
At the moment I'm banging my head against a wall and I can't quite think of what keywords to use in a google search in order to figure it out for myself.
I'd really appreciate any help on how to do this in Linq cause it seems like it should be very simple to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
或者,Mehrdad 建议的
where peopleGroup.Skip(1).Any()
通常会为 Linq to Objects 提供更好的性能,因为Count()
会迭代整个组的内容,并且Skip(1).Any()
仅在前 2 个元素上 - (有关详细信息,请参阅他的评论;Count
对于 group-by 子句来说很好)。旁白:为了便于阅读,我更喜欢始终使用
.GroupBy(...
扩展方法语法或 < code>group ... by ... into ... 查询语法,但不能同时使用两者。Alternatively,
where peopleGroup.Skip(1).Any()
as Mehrdad has suggested will generally provide better performance with Linq to Objects sinceCount()
iterates over the entire group's contents, andSkip(1).Any()
merely over the first 2 elements - (see his comment for details;Count
is fine for group-by clauses).Aside: For readability, I prefer consistently using either the
.GroupBy(...
extension method syntax or thegroup ... by ... into ...
query syntax but not both.这实际上很容易。
要按键过滤,您需要执行类似的操作。
This is actually quite easy.
To filter by key you would do something like that.