Back to: LINQ Tutorial For Beginners and Professionals
LINQ GroupBy Method with Multiple Keys in C#
In this article, I am going to discuss the LINQ GroupBy Method with Multiple Keys in C# with Examples. Please read our previous article before proceeding to this article where we discussed the Linq GroupBy Method in C# with Examples in C#. As part of this article, we will discuss the following pointers.
- Why do we need to group the data based on Multiple Keys?
- How to use the Linq GroupBy Method with Multiple Keys in C#?
- Multiple Examples using both Method and Query Syntax.
Why do we need to group the data based on Multiple Keys?
It is a very common requirement in real-time applications to group the data based on multiple keys. Now, we will see how to group the data based on multiple keys.
LINQ GroupBy Method in C# with Examples using Multiple Keys
Let us understand how to use the LINQ GroupBy Method in C# with Multiple Keys. We are going to use the following Student class to understand the GroupBy Method with Multiple Keys. 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.
using System.Collections.Generic; namespace GroupByDemo { 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 } }; } } }
Example to Understand Grouping Students Based on Multiple Keys in C#
Now, our requirement is to group the students based on Branch and gender. First, we need to group the students by Branch and then we need to group the student by Gender. Also, we need to sort the students in each group by Name in Ascending order. For a better understanding, please have a look at the following example which exactly does the same thing. The following example code is self-explained, so, please go through the comment lines.
using System; using System.Linq; namespace GroupByDemo { class Program { static void Main(string[] args) { //Using Method Syntax var GroupByMultipleKeysMS = Student.GetStudents() .GroupBy(x => new { x.Barnch, x.Gender }) .Select(g => new { Branch = g.Key.Barnch, Gender = g.Key.Gender, Students = g.OrderBy(x => x.Name) }); ; //Using Query Syntax var GroupByMultipleKeysQS = (from std in Student.GetStudents() group std by new { std.Barnch, std.Gender } into stdGroup select new { Branch = stdGroup.Key.Barnch, Gender = stdGroup.Key.Gender, //Sort the Students of Each group by Name in Ascending Order Students = stdGroup.OrderBy(x => x.Name) }); //It will iterate through each group foreach (var group in GroupByMultipleKeysQS) { Console.WriteLine($"Barnch : {group.Branch} Gender: {group.Gender} No of Students = {group.Students.Count()}"); //It will iterate through each item of a group foreach (var student in group.Students) { Console.WriteLine($" ID: {student.ID}, Name: {student.Name}, Age: {student.Age} "); } Console.WriteLine(); } Console.Read(); } } }
When you run the above code, you will get the following output.
Grouping Students Based on the Branch and Gender along with OrderBy Method
Now, our requirement is to group the students based on Branch and gender. First, we need to group the students by Branch in Descending Order and then we need to group the student by Gender in Ascending order on each branch group. Finally, the students in each group need to be sorted by their names in Ascending Order. For a better understanding, please have a look at the following example which exactly does the same thing. The following example code is self-explained, so, please go through the comment lines.
using System; using System.Linq; namespace GroupByDemo { class Program { static void Main(string[] args) { //Using Method Syntax var GroupByMultipleKeysMS = Student.GetStudents() //Group the Students first by Branch and then Gender .GroupBy(x => new { x.Barnch, x.Gender }) //Sort Each Group in Descending Order Based on Branch .OrderByDescending(g => g.Key.Barnch) //Then Sort Each Branch Group in Ascending Order Based on Gender .ThenBy(g => g.Key.Gender) //Project the Result to an Annonymous Type .Select(g => new { Branch = g.Key.Barnch, Gender = g.Key.Gender, //Sort the Students of Each group by Name in Ascending Order Students = g.OrderBy(x => x.Name) }); //Using Query Syntax var GroupByMultipleKeysQS = from student in Student.GetStudents() //Group the Students by Branch and then Gender and Store the //Result into a variable group student by new { student.Barnch, student.Gender } into stdGroup //Then Sort the group by Barnch Descending and Gender Ascending Order orderby stdGroup.Key.Barnch descending, stdGroup.Key.Gender ascending //Project the Result to an Annonymous Type select new { Branch = stdGroup.Key.Barnch, Gender = stdGroup.Key.Gender, //Sort the Students of Each group by Name in Ascending Order Students = stdGroup.OrderBy(x => x.Name) }; //It will iterate through each group foreach (var group in GroupByMultipleKeysQS) { Console.WriteLine($"Barnch : {group.Branch} Gender: {group.Gender} No of Students = {group.Students.Count()}"); //It will iterate through each item of a group foreach (var student in group.Students) { Console.WriteLine($" ID: {student.ID}, Name: {student.Name}, Age: {student.Age} "); } Console.WriteLine(); } Console.Read(); } } }
When you run the above application code, you will get the following output.
In the above example, we have projected the result to an anonymous type. If you want then you also 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 StudentGroupByBranchGender.cs and then copy and paste the following code into it.
using System.Collections.Generic; namespace GroupByDemo { public class StudentGroupByBranchGender { public string Branch { get; set; } public string Gender { 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 StudentGroupByBranchGender type instead of the anonymous type. The following example code is self-explained, so, please go through the comment lines for a better understanding.
using System; using System.Linq; namespace GroupByDemo { class Program { static void Main(string[] args) { //Using Method Syntax var GroupByMultipleKeysMS = Student.GetStudents() //Group the Students first by Branch and then Gender .GroupBy(x => new { x.Barnch, x.Gender }) //Sort Each Group in Descending Order Based on Branch .OrderByDescending(g => g.Key.Barnch) //Then Sort Each Branch Group in Ascending Order Based on Gender .ThenBy(g => g.Key.Gender) //Project the Result to StudentGroupByBranchGender Type .Select(g => new StudentGroupByBranchGender { Branch = g.Key.Barnch, Gender = g.Key.Gender, //Sort the Students of Each group by Name in Ascending Order Students = g.OrderBy(x => x.Name).ToList() }); //Using Query Syntax var GroupByMultipleKeysQS = from student in Student.GetStudents() //Group the Students by Branch and then Gender and Store the //Result into a variable group student by new { student.Barnch, student.Gender } into stdGroup //Then Sort the group by Barnch Descending and Gender Ascending Order orderby stdGroup.Key.Barnch descending, stdGroup.Key.Gender ascending //Project the Result to StudentGroupByBranchGender Type select new StudentGroupByBranchGender { Branch = stdGroup.Key.Barnch, Gender = stdGroup.Key.Gender, //Sort the Students of Each group by Name in Ascending Order Students = stdGroup.OrderBy(x => x.Name).ToList() }; //It will iterate through each group foreach (StudentGroupByBranchGender group in GroupByMultipleKeysQS) { Console.WriteLine($"Barnch : {group.Branch} Gender: {group.Gender} No of Students = {group.Students.Count()}"); //It will iterate through each item of a group foreach (var student in group.Students) { Console.WriteLine($" ID: {student.ID}, Name: {student.Name}, Age: {student.Age} "); } Console.WriteLine(); } Console.Read(); } } }
Now, run the application code, and you will get the following output as expected.
In the next article, I am going to discuss the LINQ ToLookup Method in C# with Examples. Here, in this article, I try to explain how to use the LINQ GroupBy Method with Multiple Keys in C# with Examples. I hope you enjoy this article and understand the need and use of the LINQ GroupBy with Multiple Keys in C#.
Implementation not given for above example
Thank you for letting us know. Implementation is provided. Kindly check now.
Thank you for your share.