在C#中加入2个词典

时间:2015-01-07 16:58:39

标签: c#-4.0

我有2个字典如下

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

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

如何加入这两个以便我得到以下内容:

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

我尝试dictionary1.Join(dictionary2, x=>x.Key, y=>y.Key,...)但是因为我不知道如何将它们投射到所需的形式而被阻止。

2 个答案:

答案 0 :(得分:1)

只是迭代 - 我不认为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]);

答案 1 :(得分:1)

那么你需要的不仅仅是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);