比较两个Dictionary <keyvaluepair <string,string>,int&gt;

时间:2015-12-15 08:09:54

标签: c# dictionary

我遇到了比较两个字典的相似性的问题。

我有两个类型Dictionary<KeyValuePair<string,string>,int>的词典,即

{
   [(a,b),1],
   **[(a,c),4]**,
   [(a,d),5]
}    
{
   [(x,y),5],
   **[(x,c),10]**,
   [(x,z),2]
}    

我想比较上面两个字典,这会产生另一个输出字典:

{
   [(a,c),4],
   [(x,c),10]
}

2 个答案:

答案 0 :(得分:1)

您似乎只匹配.Key.Value,因此这对您有用:

var dic1 = new Dictionary<KeyValuePair<string, string>, int>()
{
    { new KeyValuePair<string, string>("a", "b"), 1 },
    { new KeyValuePair<string, string>("a", "c"), 4 },
    { new KeyValuePair<string, string>("a", "d"), 5 },
};

var dic2 = new Dictionary<KeyValuePair<string, string>, int>()
{
    { new KeyValuePair<string, string>("x", "y"), 5 },
    { new KeyValuePair<string, string>("x", "c"), 10 },
    { new KeyValuePair<string, string>("x", "z"), 2 },
};

var query =
    from kvp1 in dic1
    join kvp2 in dic2 on kvp1.Key.Value equals kvp2.Key.Value
    from kvp in new [] { kvp1, kvp2 }
    select kvp;

var result = query.ToDictionary(x => x.Key, x => x.Value);

这让我:

result

答案 1 :(得分:0)

据我了解,您希望得到Key的{​​{1}}或Value相同的所有值。为此,您可以将KeyValuePair<string,string>方法与自定义Intersect一起使用,如下所示:

IEqualityComparer