在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 的员工列表进行排序的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。