我有一本字典
Dictionary<string, List<Employee>> employees
包含員工串列。我希望允許用戶根據他們所處的狀態按字母順序顯示員工串列。
Console.WriteLine($"If you would like to sort this list please enter one of the following choices..\n"
$"'STATE', 'INCOME', 'ID', 'NAME', 'TAX' other wise enter any key.");
var sort = Console.ReadLine().ToUpper();
var employees = EmployeeRecord.employees;
List<Employee> sortedEmps = new List<Employee>();
if (sort.Contains("STATE"))
foreach (var list in employees.Values) {
var columnQuery = list.OrderBy(x => x.stateCode).ToList();
sortedEmps.AddRange(columnQuery);
}
}
//Print out the newly ordered list
foreach (Employee r in sortedEmps) {
Console.WriteLine($"ID: {r.iD} Name: {r.name} State: {r.stateCode} Income:{r.income} Tax Due: {r.taxDue}");
}
但是,它仍然列印出串列而不對其進行排序。我怎樣才能讓它按州代碼的字母順序排序?

uj5u.com熱心網友回復:
合并所有資料后嘗試排序。
if (sort.Contains("STATE")) {
foreach (var list in employees.Values) {
sortedEmps.AddRange(list);
}
sortedEmps = sortedEmps.OrderBy(x => x.stateCode).ToList();
}
您也可以像@Robert Harvey 建議的那樣使用 SelectMany 縮短一些代碼
if (sort.Contains("STATE")) {
sortedEmps = employees.Values
.SelectMany(x => x)
.ToList().OrderBy(o => o.stateCode).ToList();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381794.html
上一篇:C#LINQ從字串陣列串列中選擇
