我有三个字典,例如
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"};
我需要将两个字典合并为一个字典
喜欢
D3[1] = {"a","b","h"}
D3[2] = {"c","d"}
D3[3] = {"e","f","l"}
合并规则:
D1[1]={"a","b"} 该列表将与 D2 中的值进行比较
D2[1]={"a","b"}
D2[5]={"b","h"}
所以上面三个会合并成
D3[1]={"a","b","h"}
有什么想法可以使用 LINQ 来做到这一点
最佳答案
但是,如果您尝试合并这些值,您可能需要使用以下选项之一:
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 中删除匹配列表将非常容易。
关于c# - 使用 LINQ 在 C# 中合并字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3156456/