Lambda或LINQ按Shift,C#</employee>对列表<employee>进行排序

时间:2011-06-01 19:35:58

标签: c# linq lambda

我有一个需要过滤的员工列表,我想看看如何使用lambda和/或LINQ表达式来做到这一点。

我想返回List中的所有Employees,但我希望它们按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);
}

编辑: Jeez你们快点!你用什么来产生这些东西?您是否正在编写它,或者是否有一个有用的工具?

3 个答案:

答案 0 :(得分:7)

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();

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

OrderByThenBy

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