2014-10-04 69 views
0

我需要按姓氏第一個字母顯示作者組列表。c#按字母組

e.g. 
A 
    Kim, Ami 
    Dim, Amaiar 
    jin, Amairaz 

B 
    Bin, Bom 
    Kin, Bomo 

C 
    Cin, Ci 
    Con, Co 

.... 

有人可以幫我解決上述問題的最佳方法是什麼?

+1

什麼是輸入?你有什麼嘗試? – Ofiris 2014-10-04 13:04:59

回答

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

您可以使用GroupBy擴展方法通過Linq對象來獲得期望的結果。

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