gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:34 26 4
gpt4 key购买 nike

我有两本字典

  Dictionary<String,List<String>> DictOne=new Dictionary<String,List<String>>()
Dictionary<String,List<String>> DictTwo=new Dictionary<String,List<String>>()

DictOne


KeyOne "A"
"B"

KeyTwo "C"
"D"

KeyThree "X"
"Y"



DictTwo

Key1 "X"
"Z"
"Y"

Key2 "A"


Key3 "C"
"D"

Key4 "M"
"N"

我需要比较和合并两个字典而不考虑键并将数据添加到第三个字典

Dictionary<String,List<String>> DictThree=new Dictionary<String,List<String>>()

所以第三个词典将包含

DictThree

KeyOne "A"
"B"

KeyTwo "C"
"D"

KeyThree "X"
"Y"
"Z"

Key4 "M"
"N"

现在我正在遍历这两个字典

现在我正在使用like

首先,我将在 DictOne 中获取第一个列表,然后搜索列表中的项目是否存在于 DictTwo 中的任何列表中,如果存在,则执行联合操作,然后使用任意一个键将结果列表添加到第三个字典中 (在 DictOne 或 DictTwo 中键入)如果列表不存在,则将列表连同键添加到第三个词典中。对 DictOne 和 DictTwo 中的所有列表执行相同的操作

有没有办法使用 LINQ 来做到这一点

提前致谢

最佳答案

哇!相当大的挑战。基本上,它们是字典这一事实完全无关紧要,您只需要 Dictionary<,>.Values每个字典的一部分,所以我将在此示例中使用一个字符串数组 ( string[][] )。

var group1 = new string[][] { new[] { "A", "B" }, new[] { "C", "D" }, new[] { "X", "Y" } };
var group2 = new string[][] { new[] { "X", "Y", "Z" }, new[] { "A" }, new[] { "C", "D" }, new[] { "M", "N" } };

// For each array in group1, check if it has matching array in group2, if
// it does, merge, otherwise just take the array as is.
var group1Join = from g1 in group1
let match = group2.SingleOrDefault(g2 => g1.Intersect(g2).Any())
select match != null ? g1.Union(match) : g1;

// Take all the group2 arrays that don't have a matching array in group1 and
// thus were ignored in the first query.
var group2Leftovers = from IEnumerable<string> g2 in group2
where !group1.Any(g1 => g2.Intersect(g1).Any())
select g2;

var all = group1Join.Concat(group2Leftovers);

编辑:更正代码以在 C# 3.0 中工作,而不依赖于 C# 4.0 的协变支持。

关于c# - 在 C# 中使用 LINQ 比较和合并字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3385110/

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