在C#合并字典 [英] Merging dictionaries in C#
问题描述
什么是合并2个或更多的字典(词典&LT
; T1,T2&GT)的最佳方式在C#中?
(3.0的功能,如LINQ的罚款)。
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和乔恩斯基特一个很酷的解决方案,但我在想东西处理重复键。在冲突的情况下,它并不重要价值,只要它的一贯被保存到字典。
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 blow up 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());
这是一个有点难看 - 和低效率的 - 但它是做在code而言最快捷的方式。 (我没有测试过,诚然。)
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屋!