gpt4 book ai didi

c# - 在 c# 中比较 2 List>

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:22 24 4
gpt4 key购买 nike

我有 2 个字典列表

List<Dictionary<string,object>> master
List<Dictionary<string,object>> sub

我的两个词典都有相同的键名。

EX: The first list Master contains
Master.Add(new Dictionary<string, string>(){

{"key1","SAME1"}
{"key2", "value1"},
{"key3","value2"}
});
Master.Add(new Dictionary<string, string>(){
{"key1","SAME2"}
{"key2", "value3"},
{"key3","value5"}
});

Master.Add(new Dictionary<string, string>(){
{"key1","SAME77"}
{"key2", "value55"},
{"key3","value44"}
});

The second list sub contains similar kind of key,value pairing :

sub.Add(new Dictionary<string, string>(){
{"key1","SAME1"}
{"key2", "value7"},
{"key3","value9"}
});

Master.Add(new Dictionary<string, string>(){
{"key1","SAME2"}
{"key2", "value3"},
{"key3","value4"}
});

在 LinQ 中有没有一种方法(或任何其他更简单的方法)我可以用来比较 2 个字典列表并获得输出字典。示例

场景 1:如您所见,我可以使用第一个词典列表中的一个键(Key1,因为它对所有人来说都是相同的值)来查看该值是否存在于第二个词典中,如果不存在,我希望丢失的词典在新列表> .

Output Ex: NewList.Add(new Dictionary<string, string>(){
{"key1","SAME77"} // since SAME77 isn't present in sub dictionary
{"key2", "value55"},
{"key3","value44"}
}

场景 2:如果假设字典子列表中的字典之一包含 key1 的相同值,我想检查同一字典的其他值,以及这些键的任何值是否已更改,如果它们有,我想要一个新的列表有原来的。

前输出:

NewList.Add(new Dictionary<string, string>(){
{"key1","SAME2"}
{"key2", "value3"},
{"key3","value5"} // since the master dictionary has value5 and the sublist dictionary has value 4

场景 1 尝试:

var result = Master.SelectMany(m=>m).Where(e=>sub.SelectMany(a=>a)
.Any(p => e.Key == p.Key && p.Value!=null && e.Value!=(p.Value)));

然而,这不会返回正确的结果,并且输出在 IEnumerable 中。我可以通过 linq 本身获得所需的输出吗?

感谢任何帮助

最佳答案

需要注意的是,您的数据结构并不理想。由于您将第一个键的第一个值视为您的“键”,您可能需要考虑重新创建结构以使用“SAME1”(和类似值)作为键。

也就是说,您仍然可以在“单行”LINQ 语句中完成这两个查询。

var masterOnly = Master.Where(m => 
!sub.Select(s => s.First().Value).Contains(m.First().Value)
).ToList();

在 master only 场景中,我们使用 Where 子句允许我们首先构建一个 sub -> first -> values 的集合,然后我们检查循环中的每个 master -> first -> value 针对该集合。如果该值不存在,我们将返回该值。

var hasChanged = Master.Where(m => 
sub.FirstOrDefault(s =>
s.First().Value == m.First().Value)?.SequenceEqual(m) == false)
.ToList();

在这种情况下,我们可以利用 C#6 的 null 传播运算符来避免需要使用 .ForEach() 在循环中构建匹配,因为如果值为 null,我们的 SequenceEquals检查被忽略。

在我们有匹配的情况下,我们想要明确地将其序列与我们的主集合进行比较,如果有任何条目不匹配,我们将其返回。

关于c# - 在 c# 中比较 2 List<Dictionary<string,object>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43358764/

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