我需要按姓氏首字母显示作者列表。
e.g.
A
Kim, Ami
Dim, Amaiar
jin, Amairaz
B
Bin, Bom
Kin, Bomo
C
Cin, Ci
Con, Co
....
有人可以帮助我解决上述问题的最佳方法吗?
答案 0 :(得分:1)
如果您想分组,请使用GroupBy,我假设您希望对输出进行排序(OrderBy),更改GroupBy
表达式以符合您的确切要求:
List<String> names = new List<String>{"Bill", "Mark", "Steve", "Amnon", "Benny"};
foreach(var g in names.GroupBy(name => name.First()).OrderBy(g => g.Key)){
Console.WriteLine(g.Key);
g.OrderBy(name => name).ToList().ForEach(Console.WriteLine);
}
将输出:
A
Amnon
B
Bill
Benny
M
Mark
S
Steve
答案 1 :(得分:1)
您可以在Linq对象上使用GroupBy扩展方法来获得所需的结果。
List<string> firstNames = new List<string>(){ "Ami", "Amaiar","Amiraz","Bom","Bomo","Ci","Co" };
var groups = firstNames.GroupBy(x=>x[0]);
foreach (var element in groups)
{
Console.WriteLine("{0}", element.Key);
foreach (var word in element)
Console.WriteLine(" {0}", word);
}