2010-11-02 45 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