在 C# 中连接多个 orderedDictionary

Join multiple orderedDictionary in C#

如何有效合并多个 orderedDictionary

在C#中,我在网上查了,但我只能看到合并NamevaluePairs的实现。

我正在尝试加入以下有序词典:

OrderedDictionary ticketToPickerMapForVerifiedTab = new OrderedDictionary();
OrderedDictionary ticketToPickerMapForHVTab = new OrderedDictionary();
OrderedDictionary ticketToPickerMapForKPTab = new OrderedDictionary();

那些字典中的键是唯一的

我需要生成的集合仍然是一个 OrderedDictionary 对象。

请注意,我的问题与此处提出的问题不同:Merging dictionaries in C#

因为那个演示了 Keyvaluepair 的情况,而我的是指使用 OrderedDictionary,因为我的代码中其他地方使用了 OrderedDictionary 的特殊功能。

您可以使用 LINQ 来合并它们。请看下面的代码:

var dictionariesMerged = ticketToPickerMapForVerifiedTab.Cast<DictionaryEntry>()
    .Union(ticketToPickerMapForHVTab.Cast<DictionaryEntry>())
    .Union(ticketToPickerMapForKPTab.Cast<DictionaryEntry>());

var dictionary = new OrderedDictionary();

foreach (DictionaryEntry tuple in dictionariesMerged)
    dictionary.Add(tuple.Key, tuple.Value);

类似于下面的 'MergeDictionaries' 方法将合并给定词典的内容。这不处理一个键存在于多个词典中的情况。

[TestFixture]
public class Class1
{

    private OrderedDictionary MergeDictionaries(params OrderedDictionary[] dictionaries)
    {
        var merged = new OrderedDictionary();
        foreach (var dictionary in dictionaries)
        {
            foreach (DictionaryEntry entry in dictionary)
            {
                merged.Add(entry.Key, entry.Value);
            }
        }
        return merged;
    }

    [Test]
    public void Test()
    {
        var d1 = new OrderedDictionary
        {
            {"x", "v1"},
            {"b", "v2"},
        };
        var d2 = new OrderedDictionary
        {
            {"d", "v3" },
            {"c", "v4" }
        };
        var d3 = new OrderedDictionary
        {
            {"z", "v5" },
            {"y", "v6" }
        };

        var merged = MergeDictionaries(d1, d2, d3);

        var expected = new OrderedDictionary
        {
            {"b", "v2"},
            {"c", "v4" },
            {"d", "v3" },
            {"x", "v1"},
            {"y", "v6" },
            {"z", "v5" }
        };

        Assert.That(merged, Is.EquivalentTo(expected));
    }
}