使用LINQ在C#中合并字典

时间:2010-07-01 09:18:01

标签: c#

我有三个像Dictonaries一样的

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"}; 

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"}; 

我需要将两个dictonary合并为一个单一的dictonary

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

合并规则:

D1 [1] = {“a”,“b”}此列表将与D2中的值进行比较

D2 [1] = { “一”, “B”}

D2 [5] = { “B”, “H”}

所以上面三个将合并到

D3 [1] = { “一”, “B”, “H”}

有任何想法使用LINQ

来做到这一点

2 个答案:

答案 0 :(得分:2)

但是,如果您尝试合并这些值,则可能需要使用以下选项之一:

D3[1] = D1[1].Union(D2[1]);

D3[1] = D1[1].Concat(D2[1]);

编辑 - 加入合并Linq风格的丑陋方法:

foreach (var kvp in D1)
{
    D3[kvp.Key] =
        (from string letter in kvp.Value
        select
            (from IEnumerable<string> list in D2.Values
            where list.Contains(letter)
            select list)
             // Union all the D2 lists containing a letter from D1.
            .Aggregate((aggregated, next) => aggregated.Union(next)))
        // Union all the D2 lists containing all the letter from D1.
        .Aggregate((aggregated, next) => aggregated.Union(next))
        // Convert the unioned letters to a List.
        .ToList();
}

代码将列表保存在D2中,修改代码以从D2中删除匹配的列表非常容易。

答案 1 :(得分:2)

这样的事情(可能需要优化)?

     var lr =
    (from gr in
        (from pair in D1.Union(D2).Union(D3)
         group pair by pair.Key)
     select new KeyValuePair<int, IEnumerable<List<string>>>(gr.Key, gr.Select(x => x.Value))
    ).ToDictionary(k => k.Key, v => v.Value.Aggregate((t, s) => (new List<string>(t.Union(s)))));
相关问题