首頁 >後端開發 >C#.Net教程 >C# 程式使用 LINQ 根據薪水對部門為 ABC 的員工清單進行排序

C# 程式使用 LINQ 根據薪水對部門為 ABC 的員工清單進行排序

WBOY
WBOY轉載
2023-09-02 10:21:02802瀏覽

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

在C#中,LINQ(Language Integrated Query)是一個強大的工具,可以輕鬆地對資料進行排序、過濾和操作。在本文中,我們將示範如何使用LINQ根據員工的薪水和部門對員工名單進行排序。

使用LINQ根據薪資和部門對員工清單進行排序

To sort a list of employees based on their salary and department using LINQ, you can follow the steps below −

1. Create a Class to Represent an Employee

public class Employee {
   public string Name { get; set; }
   public int Salary { get; set; }
   public string Department { get; set; }
}

2. Create a List of Employees

List<employee> employees = new List {
   new Employee { Name = "John", Salary = 50000, Department = "ABC" },
   new Employee { Name = "Mary", Salary = 60000, Department = "DEF" },
   new Employee { Name = "Bob", Salary = 40000, Department = "ABC" },
   new Employee { Name = "Alice", Salary = 70000, Department = "XYZ" }
};

3. Use LINQ to Sort the List of Employees by Salary and Department

var sortedEmployees = employees
   .Where(e => e.Department == "ABC")
   .OrderByDescending(e => e.Salary)
   .ThenBy(e => e.Name);

4. Iterate through the Sorted List and Print out each Employee's Name and Salary

foreach (var employee in sortedEmployees) {
   Console.WriteLine($"{employee.Name}: {employee.Salary}");
}

Explanation

的中文翻譯為:

解釋

Step 1 - 我們定義一個名為Employee的類別來表示一個員工。這個類別有三個屬性:Name(姓名),Salary(薪水)和Department(部門)。

Step 2 - We create a list of employees and initialize it with some sample data.

步驟 3 - 我們使用 LINQ 將員工清單依照薪水和部門排序。我們先篩選出部門為「ABC」的員工,然後依照薪水降序和姓名升序對篩選後的清單進行排序。結果就是一個滿足篩選條件的員工排序清單。

第四步 - 我們遍歷已排序的員工列表,並使用字串插值列印每個員工的姓名和薪水。

範例

using System;
using System.Collections.Generic;
using System.Linq;

public class Employee {
   public string Name { get; set; }
   public int Salary { get; set; }
   public string Department { get; set; }
}

class Program {
   static void Main(string[] args) {
      List<Employee> employees = new List <Employee>{
         new Employee { Name = "John", Salary = 50000, Department = "ABC" },
         new Employee { Name = "Mary", Salary = 60000, Department = "DEF" },
         new Employee { Name = "Bob", Salary = 40000, Department = "ABC" },
         new Employee { Name = "Alice", Salary = 70000, Department = "XYZ" }
      };
   
      var sortedEmployees = employees
         .Where(e => e.Department == "ABC")
         .OrderByDescending(e => e.Salary)
         .ThenBy(e => e.Name);
   
      foreach (var employee in sortedEmployees) {
         Console.WriteLine($"{employee.Name}: {employee.Salary}");
      }
   }
}

輸出

John: 50000
Bob: 40000

Conclusion

使用LINQ根據薪資和部門對員工清單進行排序是C#中操作資料的一種簡單且有效率的方式。透過使用LINQ,您可以只使用幾行程式碼就可以輕鬆地過濾、排序和操作大量的資料。我們希望本文能幫助您理解如何使用LINQ根據薪資和部門對員工名單進行排序。

以上是C# 程式使用 LINQ 根據薪水對部門為 ABC 的員工清單進行排序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除