2009-09-01 98 views
0

給定一組計數,排序依據和組LINQ

巴黎 紐約 倫敦 紐約 巴黎 巴黎

我試圖做一個LINQ查詢將返回的分組巴黎,紐約和倫敦與他們各自的計數

我已經能夠做一個GroupBy,返回一個只包含巴黎/紐約/倫敦在每個分組中的組。

聽起來相對簡單,但我不能得到它的工作?

編輯: 這不是一個家庭作業問題。

+0

可以看到你們的代碼嗎? – 2009-09-01 14:46:26

回答

9

CODE

String[] input = new [] { "Paris", "New York", "London", 
          "New York", "Paris", "Paris" }; 

var groups = input 
    .GroupBy(city => city) 
    .Select(group => new { City = group.Key, Count = group.Count() }); 

foreach(var group in groups) 
{ 
    Console.WriteLine("{0} occurs {1} time(s).", group.City, group.Count); 
} 

輸出

 
Paris occurs 3 time(s). 
New York occurs 2 time(s). 
London occurs 1 time(s). 
+0

我沒有給出完整的答案,因爲它聽起來像一個家庭作業問題。您也可以通過使用GroupBy方法的不同重載來縮短它。 – 2009-09-01 15:34:50

0

在分組上使用.Count()。