In C#, LINQ GroupBy method is used to group the items in a collection based on a key. The syntax for using GroupBy is:
main.cs56 chars2 lines
Here, collection
is the collection on which grouping is to be performed, item
is each item in the collection, and item.Key
is the property based on which grouping is to be performed. The result returned by this method is a collection of IGrouping<TKey, TElement> where TKey is the type of the key in the group and TElement is the type of the elements in the group.
Example:
main.cs794 chars28 lines
In the above example, we have a collection of students which we want to group based on gender. We use the GroupBy method to get the groups of male and female students. Finally, we loop through each group and print the students in that group.
gistlibby LogSnag