---
title: "How to use LINQ GroupBy Method in C#?"  
description: "How to use LINQ GroupBy Method in C#?"  
author: "Ethan Karla"  
published: 2021-09-24  
updated: 2021-09-24  
canonical: https://www.mindstick.com/forum/156766/how-to-use-linq-groupby-method-in-c-sharp  
category: "linq"  
tags: ["c#", "ado.net", "linq"]  
reading_time: 2 minutes  

---

# How to use LINQ GroupBy Method in C#?

How to use [LINQ](https://www.mindstick.com/articles/12007/language-integrated-query-linq-queries) [GroupBy](https://www.mindstick.com/forum/33978/how-to-use-groupby-in-linq-query) [Method in C#](https://www.mindstick.com/forum/33924/can-this-be-used-within-a-static-method-in-c-sharp) explian with example?

## Replies

### Reply by Ravi Vishwakarma

In LINQ, the **GroupBy** operator is used to grouping the list/collection items based on the specified key-value, it returns a collection of IGrouping<Key, Values>. The Groupby [method](https://www.mindstick.com/forum/166/webservice-method) in LINQ is the same as the SQL group by clause.

## Syntax

```
IEnumerable<IGrouping<key, value>> group = collection.GroupBy( condition)
```

## Example

```
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
 public static void Main()
 {
  List<Student> students = new List<Student>(){
  new Student() { StudentId = 1, Name = 'Ashu', Marks = 500 },
  new Student() { StudentId = 2, Name = 'Shyam', Marks = 500 },
  new Student() { StudentId = 3, Name = 'Shriyam', Marks = 400 },
  new Student() { StudentId = 4, Name = 'Sunny', Marks = 550 },
  new Student() { StudentId = 5, Name = 'Ram', Marks = 600 },
  new Student() { StudentId = 6, Name = 'Krishna', Marks = 550 },
  new Student() { StudentId = 7, Name = 'Anupam', Marks = 550 }
  } ;
  List<IGrouping<int, Student>> list = students.GroupBy(stu => stu.Marks).ToList();
  list.ForEach( evt => {
   Console.WriteLine('\nkey : ' + evt.Key+' No of times : ' + evt.Count() + '\n');
   Console.WriteLine('{0,-10} {1,4} {2,5}','Name','ID','Marks');
   foreach(Student student in evt){
    Console.WriteLine('{0,-10} {1,4} {2,5}',student.Name, student.StudentId,student.Marks);
   }
  }) ;
  Console.ReadLine();
 }
}
class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public int Marks { get; set; }
}
```

## Output

```
Key : 500 No of times : 2
Name         ID Marks
Ashu          1   500
Shyam         2   500
```

```
Key : 400 No of times : 1
Name         ID Marks
Shriyam       3   400
```

```
Key : 550 No of times : 3
Name         ID Marks
Sunny         4   550
Krishna       6   550
Anupam        7   550
```

```
Key : 600 No of times : 1Name         ID MarksRam           5   600
```

\


---

Original Source: https://www.mindstick.com/forum/156766/how-to-use-linq-groupby-method-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
