在C#中,LINQ(Language Integrated Query)是一个强大的工具,可以轻松地对数据进行排序、过滤和操作。在本文中,我们将演示如何使用LINQ根据员工的薪水和部门对员工列表进行排序。
To sort a list of employees based on their salary and department using LINQ, you can follow the steps below −
public class Employee { public string Name { get; set; } public int Salary { get; set; } public string Department { get; set; } }
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" } };
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}"); }
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
使用LINQ根据工资和部门对员工列表进行排序是C#中操作数据的一种简单高效的方式。通过使用LINQ,您可以仅仅使用几行代码就可以轻松地过滤、排序和操作大量的数据。我们希望本文能帮助您理解如何使用LINQ根据工资和部门对员工列表进行排序。
以上是C# 程序使用 LINQ 根据薪水对部门为 ABC 的员工列表进行排序的详细内容。更多信息请关注PHP中文网其他相关文章!