C#合并2个字典 [英] C# Merging 2 dictionaries

查看:211
本文介绍了C#合并2个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发针对.NET 3.5的C#中的应用程序。在其中,我有2个类似的字典,包含我的应用程序中特定元素集的验证标准。这两个字典具有相同的签名。第一个字典具有默认设置,第二个字典包含一些用户定义的设置。

I'm developing an app in C# targeting .NET 3.5. In it, I have 2 similar dictionaries that contain validation criteria for a specific set of elements in my app. Both dictionaries have identical signatures. The first dictionary has the default settings and the 2nd dictionary contains some user defined settings.

var default_settings = new Dictionary<string, MyElementSettings>();
var custom_settings = new Dictionary<string, MyElementSettings>();

我想将2个词典组合成一个包含两个词典元素的词典。

I would like to combine the 2 dictionaries into one that contains the elements of both dictionaries.

我遇到的问题是两个字典都有一些相同的键值。我想要的基本规则是将字典组合,如果在default_settings中已经存在的custom_settings中有任何键,custom_settings值将覆盖default_settings值。我拥有的最好的解决方案只是一个foreach循环,检查密钥是否存在于其他字典中,如果不存在,则添加它。

The problem that I am running into is it is possible for both dictionaries to have the some of the same key values. The basic rule I want is to have a combination of both dictionary and if there are any keys in the custom_settings that already exist in the default_settings, the custom_settings value will overwrite the default_settings value. The best solution i have is just a foreach loop, check if the key exists in the other dictionary, and if not, add it.

foreach (var item in custom_settings)
{
    if (default_settings.ContainsKey(item.Key))
        default_settings[item.Key] = item.Value;
    else
        default_settings.Add(item.Key, item.Value);
}

我已经完成了一些基本的LINQ查询,但我仍在努力学习更先进的东西。我已经看到一些可以合并2个字典的查询,但是大多数涉及到使用重复键对任何元素进行分组,或者只返回一个仅包含重复键的集合/是否有一个LINQ查询或表达式将模拟foreach循环的行为我正在使用?

I've done some basic LINQ queries, but I'm still working on learning the more advanced stuff. I've seen a few queries that will merge 2 dictionaries, but most involve grouping any element with duplicate keys, or only return a collection with just the duplicate keys/ Is there a LINQ query or expression that will mimic the behavior of the foreach loop I am using?

推荐答案

两点:


  1. LINQ对于执行副作用不是很好。在这种情况下,您尝试突破现有的集合而不是执行查询,因此我将避开纯LINQ解决方案。

  2. setter已经具有添加键值对的效果,如果键不存在或覆盖价值。




当您设置属性值时,如果
键在Dictionary中,则与
相关联的值将被分配的
值替换。如果密钥不在
Dictionary中,则键和
值将添加到字典。

When you set the property value, if the key is in the Dictionary, the value associated with that key is replaced by the assigned value. If the key is not in the Dictionary, the key and value are added to the dictionary.

因此,您的 foreach 循环本质上相当于:

So your foreach loop is essentially equivalent to:

foreach (var item in custom_settings)
{
   default_settings[item.Key] = item.Value;
}

现在已经很简洁了,所以我不觉得LINQ会帮助你所有这些。

Now that's pretty terse already, so I don't think LINQ is going to help you all that much.

这篇关于C#合并2个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆