如何访问linq查询返回的分组值

时间:2009-09-30 11:25:43

标签: linq c#-3.0 filtering grouping

我有以下代码:

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中有关如何做到这一点的任何帮助,因为它看起来应该很简单。

3 个答案:

答案 0 :(得分:6)

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 into peopleGroup
                          where peopleGroup.Count() > 1
                          select peopleGroup;

//get all groups where the number of people in the group is > 1

另外,Mehrdad建议的where peopleGroup.Skip(1).Any()通常会提供更好的Linq to Objects性能,因为Count()遍历整个组的内容,Skip(1).Any()仅仅覆盖前2个元素 - (有关详细信息,请参阅他的评论; Count适用于分组条款。

旁白:为了便于阅读,我更喜欢始终使用 .GroupBy(... 扩展方法语法或 group ... by ... into ... < / strong>查询语法,但不是两者。

答案 1 :(得分:2)

var peopleGroupedByName = people.GroupBy(p => p.Name)
                                .Where(g => g.Count() > 1);

var peopleGroupedByName = from p in people 
                          group p by p.Name into g
                          where g.Count() > 1
                          select g;

答案 2 :(得分:0)

实际上这很容易。

var filtererGroups = people
    .GroupBy(p => p.Name)
    .Where(grp => grp.Count() > 1);

要按键过滤,你会做类似的事情。

var filtererGroups = people
    .GroupBy(p => p.Name)
    .Where(grp => grp.Key == "Bob");