Lambda或LINQ排序列表<;员工>;按Shift,C#

本文关键字:gt Shift 员工 lt LINQ 排序 列表 Lambda | 更新日期: 2023-09-27 17:58:06

我有一个需要筛选的员工列表,我想看看如何使用lambda和/或LINQ表达式来实现这一点。

我想返回列表中的所有员工,但我希望他们按Shift、Lastname和Firstname的顺序返回。

List<Employee> empList = GetEmployeesInOtherCode();
// ...
int MAX_SHIFT = 5;
List<string> sortedNames = new List<string>(empList.Count);
for (int i = 0; i < MAX_SHIFT; i++) {
  List<string> localShift = new List<string>();
  for (int j = 0; j < empList.Count; j++) {
    Employee e = empList[j];
    if (e.Shift == i) {
      localShift.Add(string.Format("{0}, {1}", e.Lastname, e.Firstname));
    }
  }
  localShift.Sort();
  sortedNames.AddRange(localShift.ToArray());
}
foreach (string line in sortedNames) {
  Console.WriteLine(line);
}

编辑:天哪,你们快!你用什么来生成这些东西?你是手工编码的,还是有工具可以帮助你?

Lambda或LINQ排序列表<;员工>;按Shift,C#

var sortedNames = empList.Where(e => e.Shift >= 0 && e.Shift < MAX_SHIFT)
                         .OrderBy(e => e.Shift)
                         .ThenBy(e => e.LastName)
                         .ThenBy(e => e.FirstName)
                         .Select(e => string.Format("{0}, {1}", e.Lastname, e.Firstname))
                         .ToList();

为此,我更喜欢查询表达式语法:

List<string> sortedNames = (from e in empList
                            orderby e.Shift, e.LastName, e.FirstName
                            select string.Format("{0}, {1}", 
                                                  e.Lastname, 
                                                  e.Firstname)).ToList();

OrderBy和ThenBy:

empList.OrderBy(e => e.Shift).ThenBy(e => e.LastName).ThenBy(e => e.FirstName);