如何合并两个词典? [英] How do I merge two dictionaries?

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

问题描述

我需要帮助找出如何将两个词典合并在一起,创建一个。







i到目前为止这个代码:



I need help finding out how i can merge 2 dictionaries together, creating one.



i have this code so far:

using System;
using System.Collections.Generic;

namespace merging_dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>
            {
                { "WA", "Western Autralia" },
                { "NSW", "New South Wales" },
                { "SA", "South Australia" },
                { "Q", "Queensland" },
                { "V", "Victoria" },
                { "T", "Tasmania" }
            };

            Dictionary<string, string> otherdict = new Dictionary<string, string>
            {
                { "1", "Adclarkia dawsonensis" },
                { "2", "Advena campbellii " },
                { "3", "Discocharopa vigens" },
                { "4", "Hyridella glenelgensis" },
                { "5", "Mathewsoconcha grayi ms" },
                { "6", "Mathewsoconcha phillipii" }//these names are of endangered australian molusks, why not?
            };

            MergeDictionary(dict, otherdict);
        }

        public static Dictionary<string, string> MergeDictionary(Dictionary<string, string> dict1, Dictionary<string, string> dict2)
        {
            foreach (var thing in dict1)
            {
                dict2.Add(thing.Key);//make it do something with Add. 
                dict2.Add(thing.Value);//here i am trying to make it add the key and the value, but i have no idea how. 
            }
        }
    }
}





我无法完成这项工作按照预期,如果有的话。



请帮我修理一下。



谢谢。



我的尝试:



我试过不同的方法将词典放在一起但没有成功。



我尝试过不同的方法来添加键和值,一次一个或全部一起,无济于事。



I can't make this work as intended, if at all.

Please help me fix it.

Thank you.

What I have tried:

I ave tried different ways of putting the dictionaries together with no success.

I have tried different ways of adding the keys and values, one at a time or all together, to no avail.

推荐答案

检查此主题:词典 - 在C#中合并词典 - Stack Overflow [ ^ ]。合并/组合字典的方法很少。



我会通过添加一行代码来改进它们,这些代码将检查特定的 Key 是否存在。



祝你好运!
Check this thread: dictionary - Merging dictionaries in C# - Stack Overflow[^]. There's few ways to merge/combine dictionaries.

I'd improve them by adding line of code which will check if particular Key exists.

Good luck!


我需要一些不同的东西,让我指明......如果有重复的密钥...... Dictionary是从合并输出中使用的重复KeyValuePairs中获取的值的来源:
I needed something a little different that lets me specify ... in the case of duplicate Keys ... which Dictionary is the source of the value taken from the duplicate KeyValuePairs used in the merged output:
using System;
using System.Collections.Generic;
using System.Linq;

namespace WhatEver
{
    public static class DictionaryExtensions
    {
        public static Dictionary<TKey, TValue> Merge<TKey, TValue>(this Dictionary<TKey, TValue> dict1,
            Dictionary<TKey, TValue> dict2, bool useDupValueFromDict1 = true)
        {
            if (dict1.Equals(dict2)) throw new ArgumentException("duplicate dictionaries");

            if (dict1 == null) throw new ArgumentException("dictionary 1 is null");

            if (dict2 == null) throw new ArgumentException("dictionary 2 is null");

            if (dict1.Count == 0) throw new ArgumentException("dictionary 1 has no items");

            if (dict2.Count == 0) throw new ArgumentException("dictionary 2 has no items");

            Dictionary<TKey, TValue> result;
            IEnumerable<KeyValuePair<TKey, TValue>> nondups;

            if (useDupValueFromDict1)
            {
                result = dict1;
                nondups = dict2.Where(kvp => !dict1.ContainsKey(kvp.Key));

            }
            else
            {
                result = dict2;
                nondups = dict1.Where(kvp => !dict2.ContainsKey(kvp.Key));
            }

            return result.Union(nondups).ToDictionary(kvp1 => kvp1.Key, kvp1 => kvp1.Value);
        }
    }
}

另一个变体(此处未显示)允许您指定一个比较Func,它将选择使用哪个重复的KeyValuePairs。

Another variation (not shown here) lets you specify a comparison Func that will select which of the duplicate KeyValuePairs is used.


你错误地使用添加,你必须像这样使用它:

You're using Add wrongly, you have to use it like this:
dict2.Add(thing.Key, thing.Value);


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

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