GroupBy

suggest change

GroupBy is an easy way to sort a IEnumerable<T> collection of items into distinct groups.

Simple Example

In this first example, we end up with two groups, odd and even items.

List<int> iList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var grouped = iList.GroupBy(x => x % 2 == 0);

//Groups iList into odd [13579] and even[2468] items 
       
foreach(var group in grouped)
{
    foreach (int item in group)
    {
        Console.Write(item); // 135792468  (first odd then even)
    }
}

More Complex Example

Let’s take grouping a list of people by age as an example. First, we’ll create a Person object which has two properties, Name and Age.

public class Person
{
    public int Age {get; set;}
    public string Name {get; set;}
}

Then we create our sample list of people with various names and ages.

List<Person> people = new List<Person>();
people.Add(new Person{Age = 20, Name = "Mouse"});
people.Add(new Person{Age = 30, Name = "Neo"});
people.Add(new Person{Age = 40, Name = "Morpheus"});
people.Add(new Person{Age = 30, Name = "Trinity"});
people.Add(new Person{Age = 40, Name = "Dozer"});
people.Add(new Person{Age = 40, Name = "Smith"});

Then we create a LINQ query to group our list of people by age.

var query = people.GroupBy(x => x.Age);

Doing so, we can see the Age for each group, and have a list of each person in the group.

foreach(var result in query)
{
    Console.WriteLine(result.Key);
                
    foreach(var person in result)
        Console.WriteLine(person.Name);
}

This results in the following output:

20
Mouse
30
Neo
Trinity
40
Morpheus
Dozer
Smith

You can play with the live demo on .NET Fiddle

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents