2014-09-01 92 views
-2

我有一個IEnumerable與此值:[1,2,6,8,10,5,6,9,4,4,2,6,8,2,4,7,9 1,2,4] ,我想創建通過以下這一標準組值創建一個條件字典

  1. 1之間x至3,及數量的字典。
  2. x在4到7之間,然後計數。
  3. x在8和10之間,並進行計數。

我這樣做是爲了消除重複值,並計算

Dictionary<int, int> childDictionary = childArray.GroupBy(x => x) 
            .ToDictionary(g => g.Key, 
               g => g.Count()); 

的結果:

key count 
1 1 
2 4 
4 4 
5 1 
6 3 
7 1 
8 2 
9 2 
10 1 

之後,可以做同樣的解釋,但許多條件涉及GroupBy如:

//Bad code 
GroupBy(x>=1 and x<3) 
對於我早期提到的所有條件,都有

? 結果應該是這樣,假設需要針對每個條件

key count 
1 5 
2 9 
3 5 

其中一個關鍵:

  • 1是用於第一個條件
  • 2密鑰對所述第二條件
  • 關鍵
  • 3是第三個條件的關鍵
+0

說一個'for'聲明幫助? – Cullub 2014-09-01 13:10:51

+6

'GroupBy(x => x/4)'? – 2014-09-01 13:11:30

+0

如果你想統計1到3之間的所有數字,你的分組中的「key」應該是什麼? – 2014-09-01 13:17:27

回答

0

您應該返回一個不同的鍵在的GroupBy,例如使用不同的國際價值

using System; 
using System.Linq; 

var items = new int[] {1,2,6,8,10,5,6,9,4,4,2,6,8,2,4,7,9,2,4}; 

var result = items.GroupBy(x => { 
    //x between 1 to 3, and counting. 
    if (x >= 1 && x <= 3) return 1; 
    //x between 4 to 7, and counting. 
    if (x >= 4 && x <= 7) return 2; 
    //x between 8 and 10, and counted. 
    if (x >= 8 && x <= 10) return 3; 
    //else 
    return 4; 
}).ToDictionary(x => x.Key, x => x.Count()); 


foreach (var kv in result) 
{ 
    Console.WriteLine("Key = {0}, Value = {1}", kv.Key, kv.Value); 
} 

結果:

Key = 1, Value = 5 
Key = 2, Value = 9 
Key = 3, Value = 5 

演示:https://dotnetfiddle.net/wIAlrj

+0

令人驚歎!真的非常感謝!很有幫助 – 2014-09-01 13:47:50