2010-11-02 78 views
4
I have the following 

Dictionary<string,string> dict1 has 3 items 
"A"="1.1" 
"B"="2.1" 
"C"="3.1" 

Dictionary<string,string> dict2 has 3 items 
"A"="1.2" 
"B"="2.2" 
"C"="3.2" 

Dictionary<string,string> dict2 has 3 items 
"A"="1.3" 
"B"="2.3" 
"C"="3.3" 

I want a final Dict dictFinal which is of type Dictionary<string,string[]> 

"A"="1.1,1.2,1.3" 
"B"="2.1,2.2,2.3" 
"C"="3.1,3.2,3.3" 

回答

3

鑑於類似的按鍵,提供所有詞典的收集和使用SelectMany處理數組項目動態數:

var dictionaries = new[] { dict1, dict2, dict3 }; 
var result = dictionaries.SelectMany(dict => dict) 
         .GroupBy(o => o.Key) 
         .ToDictionary(g => g.Key, 
             g => g.Select(o => o.Value).ToArray()); 

dictionaries類型可能是List<T>不一定是上面的數組。重要的是你將它們集合在一個集合中,以便LINQ通過它們。

0

假設所有具有相同的鍵最straigt前進的方向是:

Dictionary<string,string[]> result = new Dictionary<string,string[]>(); 
foreach(var key in dict1.Keys) 
{ 
    result[key] = new string[]{dict1[key], dict2[key], dict3[key]}; 
} 
1

假設所有3個詞典按鍵相同,下面應該做的工作:

var d1 = new Dictionary<string, string>() 
      { 
       {"A", "1.1"}, 
       {"B", "2.1"}, 
       {"C", "3.1"} 
      }; 
var d2 = new Dictionary<string, string>() 
      { 
       {"A", "1.2"}, 
       {"B", "2.2"}, 
       {"C", "3.2"} 
      }; 

var d3 = new Dictionary<string, string>() 
      { 
       {"A", "1.3"}, 
       {"B", "2.3"}, 
       {"C", "3.3"} 
      }; 

var result = d1.Keys.ToDictionary(k => k, v => new[] {d1[v], d2[v], d3[v]}); 
+0

如果我的數組是動態的,如何在運行時添加新的d(x)[v] ...! – chugh97 2010-11-02 15:47:47

+0

@ chugh97:看看我的處理動態數組的響應。 – 2010-11-02 15:59:41