我創建了一些方法,該方法在此方法中返回Dictionary<string, List<Employee>>
i通過List<Employee>
循環並查找名字並將其按字母順序添加到我的字典中將名稱列表轉換爲字典,其中每個條目對應於以某個字母開頭的名稱
請看下面的例子:
- 員工
- Eijk,約迪
- 李四,約翰
- Doe的,簡
- 等
其中第一部分是姓氏和第二部分是姓
我的方法創建一個字典這樣
- 「D」,列表({Doe,John},{Doe,Jane})
- 「E」,List({Eijk,Jordy})
的方法:
public async Task<Dictionary<string, List<Employee>>> GetAllOrderdedByNameAsync()
{
var dbList = await _employeeRepository.ListAsync();
var employees = dbList.Select(FromDb).ToList();
var empDict = new Dictionary<string, List<Employee>>();
for (char c = 'A'; c <= 'Z'; c++)
{
var list = employees.Where(employee => employee.LastName.StartsWith(c.ToString(), StringComparison.CurrentCultureIgnoreCase)).ToList();
if (list.Count > 0)
{
empDict.Add(c.ToString(), list);
}
}
return empDict;
}
現在我的問題...有沒有更好的方式來做到這一點?我將保留List<Employee>
作爲輸入,並且需要Dictionary<string,List<Employee>>
作爲輸出,所以請不要說我需要返回其他內容。
哇,你鍵入得這麼快,是有一個優勢,使用'Substring'了'First'上'LastName'(也就是我的回答你,唯一的區別) – 2014-09-24 22:23:47
@ sa_ddam213:那麼'First'將返回一個'char'而不是'string' ....你可能在那時使用'[0]''。 – 2014-09-24 22:24:56
ahh,沒關係,'char' vs'string'會是我猜的答案:) – 2014-09-24 22:25:20