c# – 将3个词典合并为单个词典

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"
最佳答案
给定类似的键,提供所有词典的集合,并使用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());

字典类型可以是List< T>.不一定是上面的数组.重要的是你将它们组合在一个集合中以便LINQ覆盖它们.

转载注明原文:c# – 将3个词典合并为单个词典 - 代码日志