mezoid
mezoid

Reputation: 28730

How to access grouped values returned by a linq query

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.

Upvotes: 2

Views: 2802

Answers (3)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422112

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;

Upvotes: 2

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48096

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

Alternatively, where peopleGroup.Skip(1).Any() as Mehrdad has suggested will generally provide better performance with Linq to Objects since Count() iterates over the entire group's contents, and Skip(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 the group ... by ... into ... query syntax but not both.

Upvotes: 6

Daniel Br&#252;ckner
Daniel Br&#252;ckner

Reputation: 59675

This is actually quite easy.

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

To filter by key you would do something like that.

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

Upvotes: 0

Related Questions