linq query group in csharp

Here's an example of how to use LINQ to group elements in C#:

Suppose you have a list of objects that you want to group by a specific property:

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

// create a list of persons
var persons = new List<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Mike", Age = 35 },
    new Person { Name = "Sarah", Age = 30 },
    new Person { Name = "David", Age = 25 },
    new Person { Name = "Julie", Age = 35 }
};

// group persons by age
var groupedPersons = persons.GroupBy(p => p.Age);

// print out the groups
foreach (var group in groupedPersons)
{
    Console.WriteLine("Age Group: " + group.Key);
    foreach (var person in group)
    {
        Console.WriteLine("   " + person.Name);
    }
}
660 chars
29 lines

The output will be:

main.cs
Age Group: 30
   John
   Sarah
Age Group: 35
   Mike
   Julie
Age Group: 25
   David
85 chars
9 lines

In this example, persons is a list of Person objects. We use the GroupBy method to group the persons by their age property. This returns an IEnumerable of IGrouping objects. We then loop through each group and print out the age group and the names of the persons in that group.

You can also use LINQ to group by multiple properties or to perform aggregation functions on the groups.

related categories

gistlibby LogSnag