在 C# 中合并字典 [英] Merging dictionaries in C#

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

问题描述

在 C# 中合并 2 个或多个词典 (Dictionary) 的最佳方法是什么?(像 LINQ 这样的 3.0 特性很好).

What's the best way to merge 2 or more dictionaries (Dictionary<T1,T2>) in C#? (3.0 features like LINQ are fine).

我正在考虑以下方面的方法签名:

I'm thinking of a method signature along the lines of:

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);

从 JaredPar 和 Jon Skeet 那里得到了一个很酷的解决方案,但我正在考虑处理重复键的东西.在发生冲突的情况下,只要保持一致,将哪个值保存到 dict 并不重要.

Got a cool solution from JaredPar and Jon Skeet, but I was thinking of something that handles duplicate keys. In case of collision, it doesn't matter which value is saved to the dict as long as it's consistent.

推荐答案

这部分取决于您在遇到重复项时希望发生的情况.例如,你可以这样做:

This partly depends on what you want to happen if you run into duplicates. For instance, you could do:

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

如果你得到任何重复的键,这将引发异常.

That will throw an exception if you get any duplicate keys.

如果您使用 ToLookup,那么您将获得每个键可以有多个值的查找.您可以然后将其转换为字典:

If you use ToLookup then you'll get a lookup which can have multiple values per key. You could then convert that to a dictionary:

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

这有点难看 - 而且效率低下 - 但这是在代码方面最快的方法.(无可否认,我还没有测试过.)

It's a bit ugly - and inefficient - but it's the quickest way to do it in terms of code. (I haven't tested it, admittedly.)

当然,您可以编写自己的 ToDictionary2 扩展方法(使用更好的名称,但我现在没有时间去想)——这并不难,只需覆盖(或忽略)重复键即可.重要的一点(在我看来)是使用 SelectMany,并意识到字典支持对其键/值对进行迭代.

You could write your own ToDictionary2 extension method of course (with a better name, but I don't have time to think of one now) - it's not terribly hard to do, just overwriting (or ignoring) duplicate keys. The important bit (to my mind) is using SelectMany, and realising that a dictionary supports iteration over its key/value pairs.

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

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