Linq:合并词典

时间:2010-12-31 09:05:28

标签: c# linq

我在c#中有两个词典。

两个字典及其字母是

 Dictionary<int,List<string>> D1 = new Dictionary<int,List<string>>(); 
 Dictionary<int,List<string>> D2= new Dictionary<int,List<string>>(); 
 Dictionary<int,List<string>> D3 new Dictionary<int,List<string>>();
 D1[1] = new List<string>{"a","b"};
 D1[2] = new List<string>{"c","d"}; 
 D1[3] = new List<string>{"e","f"}; 
 D1[4] = new List<string>{"h"};  

其中1,2,3和4是词典D1的键

 D2[1] = new List<string>{"a","b"}; 
 D2[2] = new List<string>{"c","d"}; 
 D2[3] = new List<string>{"e","f"};
 D2[4] = new List<string>{"g"}; 
 D2[5] = new List<string>{"b","h"};
 D2[6] = new List<string>{"f","l"};
 D2[7] = new List<string>{"z"}; 

其中1,2,3,4,5,6和7是Dictionary D2的键

然后输出字典包含此值,

 D3[1] = {"a","b","h"}   D3[2] = {"c","d"}   D3[3] = {"e","f","l"} 

注意:请输入值大于1的输入字典。这就是为什么我要删除D1 [4],D2 [4]和D2 [7]

是否有可能使用LINQ合并它?

2 个答案:

答案 0 :(得分:1)

是的,它可能但它不漂亮!

//firstly lets get the keys that are valid (i.e. have more than one element in their list)
var validD1Elements = D1.Where(d => d.Value.Count > 1);
var validD2Elements = D2.Where(d => d.Value.Count > 1);

//merge the valid keys together so we know which ones we want to select
var mergedKeys = validD1Elements.Select(d => d.Key).Union(validD2Elements.Select(d => d.Key));

//perform the merge
var mergeResult = mergedKeys.Select (key => new
{
    Key = key,
    //select the values from D1
    Value = validD1Elements.Where(d => d.Key == key).SelectMany(d => d.Value)
    //concat the values from D2
    .Concat(validD2Elements.Where(d => d.Key == key).SelectMany(d => d.Value))
}).ToDictionary(e => e.Key, e => e.Value);

此合并使用Concat,因此您将获得重复项,即mergeResult[1]将为{ "a", "b", "a", "b" }

如果您不想复制,请更改以下代码:

//concat the values from D2
.Concat(validD2Elements.Where(d => d.Key == key).SelectMany(d => d.Value))

到此:

//union the values from D2
.Union(validD2Elements.Where(d => d.Key == key).SelectMany(d => d.Value))

mergeResult[1]将为{ "a", "b" }

答案 1 :(得分:0)

将它们全部concat,然后按(ToLookup)键分组,然后将分组中的所有值合并,最后将它们全部推回到字典中。