gpt4 book ai didi

c# - 使用 LINQ 在 C# 中合并字典

转载 作者:行者123 更新时间:2023-11-30 21:20:39 25 4
gpt4 key购买 nike

我有三个像这样的字典

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com