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 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 : 1 Name ID Marks Ram 5 600
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.
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 in LINQ is the same as the SQL group by clause.
Syntax
Example
Output