Web
Analytics
C# linq groupby operator with example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Linq groupby query operator able to create groups of input sequence. It is also followed concept of deferred execution , To understand deferred execution please read my blog( ).We can group output sequence using single key or multiple key, for the simplicity here I am taking example using single key(departmentname) grouping. Group can be performing using lambda expression or query expression. We can also use keyword into to assign group in proper formats.

 

In my following example I want to create groups of department name means we can create list of employees according to departments.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LINQExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee[] Employees = 
            {
                new Employee {    Name = "Ramesh", salary = 500 , departmentname="IT"},
                new Employee { Name = "Suresh", salary = 100 , departmentname="Sales"}, 
                new Employee { Name = "Yogesh", salary = 150 , departmentname="Marketting"}, 
                new Employee { Name = "Harish", salary = 500 , departmentname="HR"}, 
               new Employee { Name = "Giraj", salary = 1000 , departmentname="HR"}, 
                new Employee { Name = "Vijay", salary = 100, departmentname="IT" } };
            
            IEnumerable<IGrouping<string, Employee>> query1 = Employees.GroupBy(x => x.departmentname);
            foreach (IGrouping<string, Employee> group in query1)
            {
                Console.WriteLine("Department=" + group.Key);
                Console.WriteLine("------------------------------------------------------");
                foreach (Employee emp in group)
                {
                    Console.WriteLine("Employee Name=" + emp.Name + " Salary=" + emp.salary, " DePartment Name=" + emp.departmentname);
                    Console.WriteLine();
                }
             
            }
            Console.ReadLine();
        }
        public class Employee
        {
            public string Name;
            public int salary;
            public string departmentname;
        }


    }
}

Output

linq_groupby_operator_with_example

 

Download Source Code