将三个字典合并为一个字典

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个回答

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操作。


1

假设三个字典有相同的键,以下代码应该可以完成此任务:

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

如果我的数组是动态的,我如何在运行时添加新的 d(x)[v]…! - chugh97
@chugh97:请查看我对处理动态数组的回复。 - Ahmad Mageed

0

假设所有的键都相同,最直接的方法是:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接