Open In App

C# Program to Sort a List of Employees Based on Salary and Whose Department is ABC using LINQ

Last Updated : 06 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of employees, now our task is to sort the given list of employees based on salary and whose department is ABC using LINQ. 

Example:

Input: 
{id = 101, name = "Sumit", salary = 10000, department = ABC} 
{id = 102, name = "Rohit", salary = 20000, department = HR} 
{id = 103, name = "Mohit", salary = 30000, department = ABC} 
{id = 104, name = "Sunil", salary = 40000, department = ABC} 
Output:
{id = 101, name = "Sumit", salary = 10000, department = ABC} 
{id = 103, name = "Mohit", salary = 30000, department = ABC} 
{id = 104, name = "Sunil", salary = 40000, department = ABC} 

Approach:

1. Create a list of employees which contains the id, name, salary, and department

2. Using the OrderBy() method and Where() method to sort the list of employees based on salary and whose department is ABC

var result_set = Geeks.Where(emp => emp.Emp_Department == "ABC").OrderBy( 
                            sal  =>  sal.Emp_Salary);

3. Display the sorted list

Example:

C#




// C# program to display a sorted list of employees based 
// on Salary and whose Department is ABC 
using System;
using System.Linq;
using System.Collections.Generic;
  
public class Geek{
      
int emp_id;
string Emp_Name;
int Emp_Salary;
string Emp_Department;
  
// Driver code
static void Main(string[] args)
{
      
    // Geeks data
    List<Geek> Geeks = new List<Geek>()
    {
        new Geek{emp_id = 101, Emp_Name = "arjun"
                 Emp_Salary = 50000, Emp_Department = "ABC"},
        new Geek{emp_id = 102, Emp_Name = "bheem"
                 Emp_Salary = 65000, Emp_Department = "DEF"},
        new Geek{emp_id = 103, Emp_Name = "krishna"
                 Emp_Salary = 45000, Emp_Department = "ABC"},
        new Geek{emp_id = 104, Emp_Name = "Ram"
                 Emp_Salary = 20000, Emp_Department = "DEF"},
        new Geek{emp_id = 105, Emp_Name = "kiran"
                 Emp_Salary = 70000, Emp_Department = "DEF"},
        new Geek{emp_id = 106, Emp_Name = "karna"
                 Emp_Salary = 50000, Emp_Department = "ABC"},
    };
  
    // Using the where command we have selected the geeks
    // having ABC department and then we have sorted the
    // data using OrderBy() command
    var result_set = Geeks.Where(emp => emp.Emp_Department == "ABC").OrderBy(
                                 sal => sal.Emp_Salary);
  
    foreach (Geek emp in result_set)
    {
        Console.WriteLine(emp.emp_id + " "
                          emp.Emp_Name +" "
                          emp.Emp_Salary + " "
                          emp.Emp_Department);
    }
}
}


Output

103 krishna 45000 ABC
101 arjun   50000 ABC
106 karna 50000 ABC


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads