---
title: "How to use group by in LINQ C# and fetch the list of records?"  
description: "How to use group by in LINQ C# and fetch the list of records?"  
author: "Sandra Emily"  
published: 2023-08-17  
updated: 2023-08-18  
canonical: https://www.mindstick.com/forum/159560/how-to-use-group-by-in-linq-c-sharp-and-fetch-the-list-of-records  
category: "c#"  
tags: ["c#", "linq", "group by"]  
reading_time: 2 minutes  

---

# How to use group by in LINQ C# and fetch the list of records?

How to use [group](https://yourviews.mindstick.com/view/81323/adani-green-energy-group-bags-world-s-biggest-solar-bid) by in [LINQ](https://www.mindstick.com/articles/12007/language-integrated-query-linq-queries) C# and [fetch](https://www.mindstick.com/forum/156159/what-is-google-fetch) the list of [records](https://www.mindstick.com/forum/34640/how-to-create-a-stored-procedure-for-display-all-records)?

## Replies

### Reply by Aryan Kumar

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. 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#

```plaintext
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#

```plaintext
var records = groupedPeople.ToList();
```

In this code, the `records` variable is a list of all the `Person` objects in the `groupedPeople` object.


---

Original Source: https://www.mindstick.com/forum/159560/how-to-use-group-by-in-linq-c-sharp-and-fetch-the-list-of-records

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
