The GroupBy() method in LINQ is used to group elements in a sequence based on a common property. The
GroupBy() method returns a IGrouping<TKey, TResult> object, which is a collection of elements that have the same key.
To use the GroupBy() method, you need to specify the property that you want to group the elements by. You can also specify a lambda expression to customize the grouping.
The following code groups a list of Person objects by their age:
C#
var people = new List<Person>();
people.Add(new Person { Age = 20, Name = "John" });
people.Add(new Person { Age = 30, Name = "Jane" });
people.Add(new Person { Age = 10, Name = "Peter" });
var groupedPeople = people.GroupBy(p => p.Age);
In this code, the GroupBy() method groups the people list by the
Age property of the Person objects. The groupedPeople variable is a
IGrouping<int, Person> object, which is a collection of Person objects that have the same age.
To fetch the list of records, you can use the ToList() method. The
ToList() method returns a list of all the elements in the IGrouping object.
The following code fetches the list of records from the groupedPeople variable:
C#
var records = groupedPeople.ToList();
In this code, the records variable is a list of all the Person objects in the
groupedPeople object.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, I can help you with that.
The
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.To use the
GroupBy()method, you need to specify the property that you want to group the elements by. You can also specify a lambda expression to customize the grouping.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 fetch the list of records, you can use the
ToList()method. TheToList()method returns a list of all the elements in theIGroupingobject.The following code fetches the list of records from the
groupedPeoplevariable:C#
In this code, the
recordsvariable is a list of all thePersonobjects in thegroupedPeopleobject.