Using GroupBy in LINQ and C#

Below is a sample code snippet demonstrating how to use GroupBy in LINQ and C#.

Using GroupBy in LINQ and C#

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

namespace GinktageConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> employees = new List<Employee>();
            employees.Add(new Employee { Name = "Senthil Kumar", Experience = 6 });
            employees.Add(new Employee { Name = "Naveen", Experience = 4 });
            employees.Add(new Employee { Name = "Praveen", Experience = 1 });

            var query = from employee in employees
                    group employee by employee.Experience into ExperiencedGroup
                    let Data = from grp in ExperiencedGroup
                               select grp.Name
                    select new { Experience = ExperiencedGroup.Key, EmployeeNames = Data };
            foreach(var item in query)
            {
                Console.WriteLine("Experience : " + item.Experience + "\n");
                foreach(var item1 in item.EmployeeNames)
                    Console.WriteLine(item1);
                
            }
            Console.ReadLine();
        }
    }
    public class Employee
    {
        public string Name { get; set; }
        public int Experience { get; set; }
    }
}

image

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply


x

Interesting BlogPosts to read

How to perform Shallow Copy in C# ? by @abundantcode
To perform Shallow copy in C# , you can use the this.MemberwiseClone() method. How to perform Shall...
How to add entries to ResourceDirectory in WPF using C# ?
Below is a sample code snippet demonstrating how the entries can be added to the ResourceDirectory i...
Replacing Multiple spaces with single space in C#
Are you looking at an sample demonstrating the usage of the regular expression to replace multiple s...