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.cs660 chars29 lines
The output will be:
main.cs85 chars9 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.
gistlibby LogSnag