[英]Lambda or LINQ to Sort List<Employee> by Shift, C#
I have a List of Employee that I need to filter, and I'd like to see how to do this using a lambda and/or LINQ expression.我有一个需要过滤的员工列表,我想看看如何使用 lambda 和/或 LINQ 表达式来执行此操作。
I want to return ALL of the Employees in the List, but I want them returned in order of Shift, Lastname, and Firstname.我想返回列表中的所有员工,但我希望它们按 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);
}
EDIT: Jeez you guys are fast?编辑:天哪,你们很快? What do you use to generate this stuff, Are you hand coding it?你用什么来生成这些东西,你是手工编码的吗? or is there a tool out there that helps?或者有没有帮助的工具?
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();
For this I like query expression syntax better:为此,我更喜欢查询表达式语法:
List<string> sortedNames = (from e in empList
orderby e.Shift, e.LastName, e.FirstName
select string.Format("{0}, {1}",
e.Lastname,
e.Firstname)).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.