gpt4 book ai didi

c# - 使用 LINQ 合并两个字典

转载 作者:IT王子 更新时间:2023-10-29 04:26:22 28 4
gpt4 key购买 nike

我的问题已被标记为可能与此问题重复:How to combine two dictionaries without looping?

我相信我的问题是不同的,因为我在问如何以特定方式组合两个词典:我想要 Dictionary1 中的所有项目加上 Dictionary2 中不在(即键不存在)在 Dictionary1 中的所有项目。

我有两本这样的字典:

var d1 = new Dictionary<string,object>();
var d2 = new Dictionary<string,object>();

d1["a"] = 1;
d1["b"] = 2;
d1["c"] = 3;

d2["a"] = 11;
d2["e"] = 12;
d2["c"] = 13;

我想将它们组合成一个新的字典(从技术上讲,它不必是一个字典,它可以只是一个 KeyValuePairs 的序列)这样输出就包含了所有的 KeyValuePairs来自 d1 且仅来自 d2 的 KeyValuePairs d1 中没有出现其 Key .

概念上:

var d3 = d1.Concat(d2.Except(d1))

但这给了我 d1 和 d2 中的所有元素。

看起来应该很明显,但我一定遗漏了什么。

最佳答案

当您默认使用 Except 时,它使用默认的相等比较器,对于 KeyValuePair 类型,它会同时比较键和值。您可以改用这种方法:

var d3 = d1.Concat(d2.Where(kvp => !d1.ContainsKey(kvp.Key)));

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

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