Hello friends, In this tutorial, We are going to understand Max operator in Linq. Like SQL Server Linq also have the ability to perform max over the collection.

Max Operator in Linq:

Max operator is used for returning the largest numeric element from a collection.

Example 1:

Find the largest element in a collection.

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


class Program
{
static void Main(string[] args)
{
IList<int> lstNumber = new List<int>() { 44, 33, 54, 23, 11, 34 };

var vLargestNumber = lstNumber.Max();

Console.WriteLine("Largest Element: {0}", vLargestNumber);
Console.ReadLine(); 
}
 
}

Output:

Largest Element: 54

Example 2: Max salary for an employee-

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


public class Employee
{
public string EmployeeCode { get; set; }
public string EmployeeName { get; set; }
public string Gender { get; set; }
public string Designation { get; set; }
public double Salary { get; set; }
}

class Program
{
public static List<Employee> DataSource()
{
List<Employee> lstEmployee = new List<Employee>();
Employee objEmployee1 = new Employee() { EmployeeCode = "E001", EmployeeName = "Ayush Singh", Gender = "Male", Designation = "Software Engineer", Salary = 30000 };
Employee objEmployee2 = new Employee() { EmployeeCode = "E002", EmployeeName = "Ritwik Nigam", Gender = "Male", Designation = "Software Engineer", Salary = 30000 };
Employee objEmployee3 = new Employee() { EmployeeCode = "E003", EmployeeName = "Nikhil Bakshi", Gender = "Male", Designation = "Team Lead", Salary = 60000 };
Employee objEmployee4 = new Employee() { EmployeeCode = "E004", EmployeeName = "Nidhi Verma", Gender = "Female", Designation = "HR", Salary = 40000 };
Employee objEmployee5 = new Employee() { EmployeeCode = "E005", EmployeeName = "Ayushman Lakhotia", Gender = "Male", Designation = "Project Manager", Salary = 80000 };
Employee objEmployee6 = new Employee() { EmployeeCode = "E006", EmployeeName = "Neha Sharma", Gender = "Female", Designation = "Graphic Designer", Salary = 25000 };
lstEmployee.Add(objEmployee1);
lstEmployee.Add(objEmployee2);
lstEmployee.Add(objEmployee3);
lstEmployee.Add(objEmployee4);
lstEmployee.Add(objEmployee5);
lstEmployee.Add(objEmployee6);
return lstEmployee;
}
static void Main(string[] args)
{
 
var vHighestPaidSalary = DataSource().Max(e=>e.Salary);

Console.WriteLine("Highest Paid Salary is: {0}", vHighestPaidSalary);
Console.ReadLine(); 
}
 
}

Output:

Highest Paid Salary is: 80000

View More:

Conclusion:

I hope you would love this post. please don’t hesitate to comment for any technical help. Your feedback and suggestions are always welcome to me.

Thank You.

Leave a Comment