代码之家  ›  专栏  ›  技术社区  ›  mezoid

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

  •  2
  • mezoid  · 技术社区  · 15 年前

    我有以下代码:

    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中实现这一点的帮助,因为它看起来应该非常简单。

    3 回复  |  直到 15 年前
        1
  •  6
  •   mezoid    15 年前
    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
    

    或者, where peopleGroup.Skip(1).Any() 正如Mehrdad所建议的,自 Count() 迭代整个组的内容,并且 Skip(1).Any() Count 对于group by子句是可以的)。

    旁白: 为了可读性,我更喜欢一致地使用 .GroupBy(... 扩展方法语法或 group ... by ... into ... 查询语法,但不是两者都有。

        2
  •  2
  •   mezoid    15 年前
    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;
    
        3
  •  0
  •   Daniel Brückner    15 年前

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

    要按键过滤,您可以执行类似的操作。

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