How to access grouped values returned by linq query
I have 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
Throughout my life, I can't figure out how to work with the values returned by a linq query, so that I can then filter all the groups that were returned, so that I only have groups that have more than one in them.
At the moment I'm banging my head against the wall and I can't remember what keywords to use in Google searches to figure this out for myself.
I would really appreciate any help on how to do this in Linq, because it seems like it should be very simple.
source to share
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 suggested by Mehrdad, it usually provides better performance with Linq to Objects because it Count()
iterates over the entire content of the group rather Skip(1).Any()
than the first two elements only (see his comment Count
for details; great for group suggestions).
Also: For readability, I prefer to use method syntax or query syntax sequentially , but not both. .GroupBy(...
group ... by ... into ...
source to share