首页 / C#开发 / 正文

[C#].NET/C#程序开发中将多个字典合并成一个字典的方法有哪些?

12751 发布于: 2018-02-27 读完约需9分钟

.NET&&C#程序开发

问题描述

在C#/.NET程序开发中,我哪些好的方式来实现将两个或者多个字典合并成一个字典?比如以下的伪代码:

public static Dictionary<TKey,TValue>
                 Merge<TKey,TValue>(Dictionary<TKey,TValue>[] dictionaries);

或者

public static Dictionary<TKey,TValue>
                 Merge<TKey,TValue>(IEnumerable<Dictionary<TKey,TValue>> dictionaries);

在.NET 3.0 及以上版本中,我们可以使用LINQ方便地实现,除此之外还有哪些方法呢?

方案一

可以使用SelectMany(...)方法,如:

var result = dictionaries.SelectMany(dict => dict)
                         .ToDictionary(pair => pair.Key, pair => pair.Value);

但是,如果不同字典中有相同的Key,则会发生异常。所以,我们可以使用ToLookup()方法先处理一下,如:

var result = dictionaries.SelectMany(dict => dict)
                         .ToLookup(pair => pair.Key, pair => pair.Value)
                         .ToDictionary(group => group.Key, group => group.First());

方案二

循环第一个字典,将第二个字典中的数据添加到第一个字典,具体操作如下:

dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));

注:当两个字典中有相同Key的时候,同样会发生异常,所以,在合并之前,请处理有相同Key的情况。

方案三

创建一个字典合并的静态扩展方法,如:

public static class DictionaryExtensions
{
    public static T MergeLeft<T,K,V>(this T me, params IDictionary<K,V>[] others)
        where T : IDictionary<K,V>, new()
    {
        T newMap = new T();
        foreach (IDictionary<K,V> src in
            (new List<IDictionary<K,V>> { me }).Concat(others)) {
            foreach (KeyValuePair<K,V> p in src) {
                newMap[p.Key] = p.Value;
            }
        }
        return newMap;
    }
}

调用方法:

result = map.MergeLeft(other1, other2, ...)

方案四

常规的解决方案:

using System.Collections.Generic;
...
public static Dictionary<TKey, TValue>
    Merge<TKey,TValue>(IEnumerable<Dictionary<TKey, TValue>> dictionaries)
{
    var result = new Dictionary<TKey, TValue>();
    foreach (var dict in dictionaries)
        foreach (var x in dict)
            result[x.Key] = x.Value;
    return result;
}

方案五

使用Union()方法连接两个字典,如:

Dictionary<String, String> allTables = new Dictionary<String, String>();
allTables = tables1.Union(tables2).ToDictionary(pair => pair.Key, pair => pair.Value);

或者:

public static IDictionary<TKey, TValue> Merge<TKey, TValue>(this IDictionary<TKey, TValue> dictA, IDictionary<TKey, TValue> dictB)
    where TValue : class
{
    return dictA.Keys.Union(dictB.Keys).ToDictionary(k => k, k => dictA.ContainsKey(k) ? dictA[k] : dictB[k]);
}

方案六

创建一个静态扩展方法,如:

using System.Collections.Generic;
namespace HelperMethods
{
    public static class MergeDictionaries
    {
        public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)
        {
            if (second == null || first == null) return;
            foreach (var item in second) 
                if (!first.ContainsKey(item.Key)) 
                    first.Add(item.Key, item.Value);
        }
    }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [C#].NET/C#程序开发中如何更优美地实现失败任务重试的逻辑?

下一篇: [C#].NET/C#程序开发如何为一个数组添加值有哪些方法?

本文永久链接码友网 » [C#].NET/C#程序开发中将多个字典合并成一个字典的方法有哪些?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册