What is LINQ GroupBy Method in C#?
The LINQ GroupBy Method in C# belongs to the Grouping Operators Category. This method exactly does the same thing as the Group By clause does in SQL Query. This method takes a flat sequence of elements and then organizes the elements into groups (i.e. IGrouping<TKey, TSource>) based on a given key. That means that based on the given key, it will group the elements.
If you go to the definition of the GroupBy method then you will see that it returns an IEnumerable<IGrouping<TKey, TSource>> where TKey is nothing but the Key value on which the grouping has been formed and TSource is the collection of elements that matches the grouping key value. If this is not clear at the moment then don’t worry, let us try to understand this with some examples.
LINQ GroupBy Method in C# with Examples
Let us understand how to use the LINQ GroupBy Method in C# using both Method and Query Syntax with some examples. We are going to use the following Student class to understand the GroupBy Method. So, create a class file with the name Student.cs and then copy and paste the following code into it. This is a very simple class having five properties such as ID, Name, Gender, Branch, and Age. This class also has one method called GetStudents() which returns a list of all students and this is going to be our data source.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using System.Collections.Generic; namespace LinqDemo { public class Student { public int ID { get; set; } public string Name { get; set; } public string Gender { get; set; } public string Barnch { get; set; } public int Age { get; set; } public static List<Student> GetStudents() { return new List<Student>() { new Student { ID = 1001, Name = "Preety", Gender = "Female", Barnch = "CSE", Age = 20 }, new Student { ID = 1002, Name = "Snurag", Gender = "Male", Barnch = "ETC", Age = 21 }, new Student { ID = 1003, Name = "Pranaya", Gender = "Male", Barnch = "CSE", Age = 21 }, new Student { ID = 1004, Name = "Anurag", Gender = "Male", Barnch = "CSE", Age = 20 }, new Student { ID = 1005, Name = "Hina", Gender = "Female", Barnch = "ETC", Age = 20 }, new Student { ID = 1006, Name = "Priyanka", Gender = "Female", Barnch = "CSE", Age = 21 }, new Student { ID = 1007, Name = "santosh", Gender = "Male", Barnch = "CSE", Age = 22 }, new Student { ID = 1008, Name = "Tina", Gender = "Female", Barnch = "CSE", Age = 20 }, new Student { ID = 1009, Name = "Celina", Gender = "Female", Barnch = "ETC", Age = 22 }, new Student { ID = 1010, Name = "Sambit", Gender = "Male",Barnch = "ETC", Age = 21 } }; } } } |
Grouping the Students Based on the Branch
Now, our requirement is to group the students based on Branch. For a better understanding, please have a look at the following example which exactly does the same thing. The following example organizes the students into groups based on their branch (i.e. branch will act as the key). It also means that students with the same branch will be stored in the same group where each group has a key and the corresponding student collection. Here, the key will be the Branch and the collection will be the student belonging to that particular branch. The following example code is self-explained, so, please go through the comment lines. In the below example, I am showing how to use GroupBy Method using both Method Syntax and Query Syntax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System; using System.Linq; using System.Collections.Generic; namespace LinqDemo { class Program { static void Main(string[] args) { //Using Method Syntax IEnumerable<IGrouping<string, Student>> GroupByMS = Student.GetStudents().GroupBy(s => s.Barnch); //Using Query Syntax IEnumerable<IGrouping<string, Student>> GroupByQS = (from std in Student.GetStudents() group std by std.Barnch); //It will iterate through each groups foreach (IGrouping<string, Student> group in GroupByMS) { Console.WriteLine(group.Key + " : " + group.Count()); //Iterate through each student of a group foreach (var student in group) { Console.WriteLine(" Name :" + student.Name + ", Age: " + student.Age + ", Gender :" + student.Gender); } } Console.Read(); } } } |
Note: Each group has a key and you can access the value of the key by using the key property. Along the same line, you can use the count property to check how many elements are there in that group. Again, using a for each loop, you can access all the elements of a group which is shown in the above example.
Grouping Students by Gender in Descending Order, Names in Ascending Order in Each Group
Let us see an example to Understand the LINQ GroupBy Method with the following Requirements.
- First, Grouping the Students by Gender.
- Sort the Groups in Descending Order i.e. soring the gender in Descending Order.
- Finally, Sort the Student Names in each group in Ascending Order.
In the following example, we group the students by Gender using the LINQ GroupBy Method. Then, we sort the data by Gender in descending order and finally, we sort the students in each group by their name in Ascending Order. The following example code is self-explained, so please go through the comment lines.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | using System; using System.Linq; namespace LinqDemo { class Program { static void Main(string[] args) { //Using Method Syntax //First Group the Data by Gender var GroupByMS = Student.GetStudents().GroupBy(s => s.Gender) //Then Sorting the data based on key in Descending Order .OrderByDescending(c => c.Key) .Select(std => new { Key = std.Key, //Sorting the Students in Each Group based on Name in Ascending order Students = std.OrderBy(x => x.Name) }); //Using Query Syntax //First Group the Data by Gender var GroupByQS = from std in Student.GetStudents() //First store the data into a group group std by std.Gender into stdGroup //Then Sorting the data based on key in Descending Order orderby stdGroup.Key descending select new { Key = stdGroup.Key, //Sorting the Students in Each Group based on Name in Ascending order Students = stdGroup.OrderBy(x => x.Name) }; //It will iterate through each groups foreach (var group in GroupByQS) { Console.WriteLine(group.Key + " : " + group.Students.Count()); //Iterate through each student of a group foreach (var student in group.Students) { Console.WriteLine(" Name :" + student.Name + ", Age: " + student.Age + ", Branch :" + student.Barnch); } } Console.Read(); } } } |
In the above example, the result is projected to an anonymous type. If you want then you create a new type with the required properties and then you can project the result to that new type. Let us understand this. First, create a class file with the name StudentGroup.cs and then copy and paste the following code into it.
1 2 3 4 5 6 7 8 9 10 11 12 | using System.Collections.Generic; namespace LinqDemo { public class StudentGroup { public string Key { get; set; } public List<Student> Students { get; set; } } } |
With the above changes in place, now modify the Main method of the Program class as follows. Here, you can see, we are projecting the result into the newly created StudentGroup type instead of the anonymous type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | using System; using System.Linq; namespace GroupByDemo { class Program { static void Main(string[] args) { //Using Method Syntax //First Group the Data by Gender var GroupByMS = Student.GetStudents().GroupBy(s => s.Gender) //Then Sorting the data based on key in Descending Order .OrderByDescending(c => c.Key) .Select(std => new StudentGroup { Key = std.Key, //Sorting the Students in Each Group based on Name in Ascending order Students = std.OrderBy(x => x.Name).ToList() }); //Using Query Syntax //First Group the Data by Gender var GroupByQS = from std in Student.GetStudents() //First store the data into a group group std by std.Gender into stdGroup //Then Sorting the data based on key in Descending Order orderby stdGroup.Key descending select new StudentGroup { Key = stdGroup.Key, //Sorting the Students in Each Group based on Name in Ascending order Students = stdGroup.OrderBy(x => x.Name).ToList() }; //It will iterate through each groups foreach (var group in GroupByQS) { Console.WriteLine(group.Key + " : " + group.Students.Count()); //Iterate through each student of a group foreach (var student in group.Students) { Console.WriteLine(" Name :" + student.Name + ", Age: " + student.Age + ", Branch :" + student.Barnch); } } Console.Read(); } } } |
In the next article, I am going to discuss LINQ GroupBy Method with Multiple Keys in C# with Examples. In this article, I try to explain the LINQ GroupBy Methid in C# with Examples. I hope you understood what the need is and how to use the LINQ Groupby Method in C# along with OrderBy Method with Examples.
Leave a Comment