How to get the MAX row with group by in LINQ query using C# ?

Below is a sample code snippet demonstrating how to retreive the max row with the group by in LINQ Query using C# .

For example , assume that the table name is employee and we want to retreive the maximum experience based on the designation .

In SQL Query , we would do something like this

Select max(experience) as experience, Designation from Employee Group BY Designation

How to get the MAX row with group by in LINQ query using C# ?

using System;
using System.Collections.Generic;
using System.Linq;
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 = "Rajni", Experience = 6 , Designation="Senior Software Engineer" });
            employees.Add(new Employee { Name = "Naveen", Experience = 4, Designation = "Senior Software Engineer" });
            employees.Add(new Employee { Name = "Praveen", Experience = 1, Designation = "Trainee" });
            employees.Add(new Employee { Name = "Michael", Experience = 4, Designation = "Software Engineer" });
            var query = from employee in employees
                    group employee by employee.Designation
                        into g
                    select new
                    {
                        Designation = g.Key,
                        Experience = (from exp in g select exp.Experience).Max()
                    };

        }
    }
    public class Employee
    {
        public string Name { get; set; }
        public int Experience { get; set; }
        public string Designation { get; set; }
    }
}


image

Leave A Reply

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...