How to use Group by in LINQ?
How to use Group by in LINQ?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
18-Aug-2023The
GroupBy()method in LINQ is used to group elements in a sequence based on a common property. TheGroupBy()method returns aIGrouping<TKey, TResult>object, which is a collection of elements that have the same key.The syntax for the
GroupBy()method is as follows:sequence: The sequence of elements to be grouped.keySelector: A delegate that returns the key for each element.elementSelector: An optional delegate that returns the element to be included in the group.The
keySelectordelegate is required. TheelementSelectordelegate is optional. If theelementSelectordelegate is not specified, the entire element is used as the group key.The following code groups a list of
Personobjects by their age:C#
In this code, the
GroupBy()method groups thepeoplelist by theAgeproperty of thePersonobjects. ThegroupedPeoplevariable is aIGrouping<int, Person>object, which is a collection ofPersonobjects that have the same age.To iterate through the
groupedPeopleobject, you can use a foreach loop:C#
In this code, the foreach loop iterates through the
groupedPeopleobject and prints the age and name of each person in the group.