---
title: "How to use Group by in LINQ?"  
description: "How to use Group by in LINQ?"  
author: "Steilla Mitchel"  
published: 2023-08-17  
updated: 2023-08-18  
canonical: https://www.mindstick.com/forum/159559/how-to-use-group-by-in-linq  
category: "c#"  
tags: ["c#", "linq"]  
reading_time: 2 minutes  

---

# How to use Group by in LINQ?

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)?

## Replies

### Reply by Aryan Kumar

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.

The syntax for the `GroupBy()` method is as follows:

```plaintext
sequence.GroupBy(keySelector, [elementSelector])
```

- `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 `keySelector` delegate is required. The `elementSelector` delegate is optional. If the `elementSelector` delegate is not specified, the entire element is used as the group key.

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 iterate through the `groupedPeople` object, you can use a foreach loop:

C#

```plaintext
foreach (var group in groupedPeople) {
    Console.WriteLine(group.Key);
    foreach (var person in group) {
        Console.WriteLine(person.Name);
    }
}
```

In this code, the foreach loop iterates through the `groupedPeople` object and prints the age and name of each person in the group.


---

Original Source: https://www.mindstick.com/forum/159559/how-to-use-group-by-in-linq

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
