在 C# 中加入 2 个字典

Joining 2 dictionaries in C#

我有2本字典如下

Dictionary<string,int> (values are unique as well)
{"xyz", 123}
{"abc", 456}

Dictionary<string,CustomObject>
{"xyz", instanceOfCustomObject1}
{"abc", instanceOfCustomObject2}

我如何加入这 2 个才能得到以下内容:

Dictionary<int,CustomObject>
{123, instanceOfCustomObject1}
{456, instanceOfCustomObject2}

我试过 dictionary1.Join(dictionary2, x=>x.Key, y=>y.Key,...) 但'被阻止了,因为我不知道如何将它们投影成所需的形式。

只是迭代——我认为 Linq 在这里不会给你带来太多好处:

public Dictionary<int, CustomObject> Combine(Dictionary<string, int> first, Dictionary<string, CustomObject> second)
{
    var result = new Dictionary<int, CustomObject>();
    foreach (string key in first.Keys)
        if (second.ContainsKey(key))
            result.Add(first[key], second[key]);
    return result;
}

或者如果您愿意:

    foreach (string key in first.Keys.Union(second.Keys))
        result.Add(first[key], second[key]);

好吧,您需要的不仅仅是 Join()。将其与对 ToDictionary().

的调用配对
Dictionary<string, int> dictionary1 = ..;
Dictionary<string, CustomObject> dictionary2 = ...;
var dict = dictionary1.Join(dictionary2, d1 => d1.Key, d2 => d2.Key,
                            (d1, d2) => new { Key = d1.Value, Value = d2.Value })
    .ToDictionary(x => x.Key, x => x.Value);