C# Program to Sort a List of Employees Based on Salary in Descending Order and Whose Department is XYZ using LINQ

• Difficulty Level : Hard
• Last Updated : 06 Dec, 2021

Given a list of employees, now we sort the list according to the salary in descending order and whose department is XYZ. So we use the OrderByDescending() method of LINQ along with the Where() method. The OrderByDescending() is used to sort the specified list in descending order. To solve the given problem we use the following LINQ query:

var result_set = Geeks.Where(emp=>emp.Emp_Department==”XYZ”).OrderByDescending(sal => sal.Emp_Salary);

Here, the Where() method finds those employees whose department is “XYZ” and OrderByDescending() method sort them in descending order based on their salary.

Example:

Input: {id = 202, Name = Mohit, Salary = 10000, Depertment = XYZ}
{id = 204, Name = Sumit, Salary = 20000, Depertment = ABC}
{id = 205, Name = Pritam, Salary = 80000, Depertment = ABC}
{id = 206, Name = Poonam, Salary = 30000, Depertment = XYZ}
Output: {id = 206, Name = Poonam, Salary = 30000, Depertment = XYZ}
{id = 202, Name = Mohit, Salary = 10000, Depertment = XYZ}

C#

 // C# program to sort a list of employees based on // salary in descending order and whose department is XYZusing System;using System.Linq;using System.Collections.Generic;  class Geek{      int emp_id;string Emp_Name;int Emp_Salary;string Emp_Department;  static void Main(string[] args){          // List to store the details of employees    List Geeks = new List()    {        new Geek{emp_id = 101, Emp_Name = "Amit",                  Emp_Salary = 50000,Emp_Department = "XYZ"},        new Geek{emp_id = 102, Emp_Name = "Poonam",                  Emp_Salary = 65000,Emp_Department = "ABC"},        new Geek{emp_id = 103, Emp_Name = "Priya",                  Emp_Salary = 45000,Emp_Department = "ABC"},        new Geek{emp_id = 104, Emp_Name = "Sita",                  Emp_Salary = 20000,Emp_Department = "XYZ"},        new Geek{emp_id = 105, Emp_Name = "kiran",                  Emp_Salary = 70000,Emp_Department = "ABC"},        new Geek{emp_id = 106, Emp_Name = "Sohan",                  Emp_Salary = 40000,Emp_Department = "XYZ"},    };      // Using the where command we have selected the    // geeks having XYZ department and then we have     // sorted the data in descending order using     // OrderByDescending() command    var result_set = Geeks.Where(emp => emp.Emp_Department == "XYZ").OrderByDescending(                                 sal => sal.Emp_Salary);                                       // Display the results    foreach (Geek emp in result_set)    {        Console.WriteLine(emp.emp_id + " " +                           emp.Emp_Name + " " +                           emp.Emp_Salary + " " +                           emp.Emp_Department);    }}}

Output:

101 Amit 50000 XYZ
106 Sohan 40000 XYZ
104 Sita 20000 XYZ

My Personal Notes arrow_drop_up