📌  相关文章
📜  C# 程序使用 LINQ 根据薪水和部门为 ABC 对员工列表进行排序

📅  最后修改于: 2022-05-13 01:55:47.429000             🧑  作者: Mango

C# 程序使用 LINQ 根据薪水和部门为 ABC 对员工列表进行排序

给定一个员工列表,现在我们的任务是使用 LINQ 根据薪水和部门为 ABC 对给定的员工列表进行排序。

例子:

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} 

方法:

1.创建包含id、姓名、薪水和部门的员工列表

2 、使用OrderBy()方法和Where()方法对员工列表按工资排序,部门为ABC

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

3.显示排序列表

例子:

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 Geeks = new List()
    {
        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);
    }
}
}


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