Linq GroupBy Method

Linq GroupBy Method in C# with Examples

In this article, I am going to discuss the Linq GroupBy Method in C# with some examples. Please read our previous article before proceeding to this article where we discussed the Linq Contains Method in C# with examples. As part of this article, we will discuss the following two things.

  1. What is Linq GroupBy Method in C#?
  2. How to use the Linq GroupBy Method using both Query and Method Syntax?
  3. How to use the GroupBy Method along with OrderBy Method in C# using both Method and Query Syntax?
What is Linq GroupBy Method?

The Linq GroupBy Method in C# belongs to the Grouping Operators category and 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.

If you go the definition of GroupBy method then you will see that it return 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.

Helper class used in this demo:

Let us first create a helper class file with the name Student.cs and then copy and paste the following code in it.

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:

The following example organizes the students into groups based on their branch (i.e. branch will act as the key). That means students with the same branch will be stored in the same group where each group having a key and an inner collection. Here, the key will be branch and the collection will be the student belongs to that particular branch.

Note: Please go through the comment line which is self-explained.

using System;
using System.Collections.Generic;
using System.Linq;

namespace GroupByDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Method Syntax
            var 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(var 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();
        }
    }  
}

Output:

GroupBy in Linq

Note: Each group has a key and you can access the key value 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.

Example:

In the following example, we get the employees by Gender. But here we first sort the data by Gender in descending order and then sort the student by their name in ascending order.

using System;
using System.Linq;

namespace GroupByDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Method Syntax
            var GroupByMS = Student.GetStudents().GroupBy(s => s.Gender)
                            //First sorting the data based on key in Descending Order
                            .OrderByDescending(c => c.Key) 
                            .Select(std => new
                            {
                                Key = std.Key,
                                //Sorting the data based on name in descending order
                                Students = std.OrderBy(x => x.Name)
                            });

            //Using Query Syntax
            var GroupByQS = from std in Student.GetStudents()
                                group std by std.Gender into stdGroup
                                orderby stdGroup.Key descending
                                select new
                                {
                                    Key = stdGroup.Key,
                                    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();
        }
    }  
}

Output:

GroupBy in Linq With OrderBy Operator

Note: Here the result is projected to an anonymous type.

In the next article, I am going to discuss how to use the Group By Method with Multiple Keys in C#. In this article, I try to explain the Linq GroupBy Method with some examples. I hope you understood what the need is and how to use the Group by Method in Linq along with the OrderBy Method.

Leave a Reply

Your email address will not be published. Required fields are marked *