使用 LINQ 根据薪资对员工列表进行排序的 C# 程序
在许多软件开发项目中,有时需要根据对象的一个或多个属性对对象列表进行排序。在 C# 中,LINQ(语言集成查询)库提供了一种强大且易于使用的方法来根据一个或多个条件对对象列表进行排序。在本教程中,我们将演示如何使用 LINQ 根据工资对 Employee 对象列表进行排序。
步骤
创建一个 Employee 类,其中包含姓名、薪水和部门属性。
创建 Employee 对象列表并用一些数据填充它。
使用 LINQ 根据工资对 Employee 对象列表进行排序。
显示 Employee 对象的排序列表。
示例
以下是示例程序的 C# 代码,该程序使用 LINQ 根据员工的工资对员工列表进行排序 -
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 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 = "XYZ" }, new Employee { Name = "Alice", Salary = 70000, Department = "XYZ" } }; var sortedEmployees = employees .OrderByDescending(e => e.Salary); foreach (var employee in sortedEmployees) { Console.WriteLine($"{employee.Name}: {employee.Salary}"); } } } 登录后复制