在C#字典之间测试相等 [英] Testing for equality between dictionaries in c#

查看:164
本文介绍了在C#字典之间测试相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设词典键和值有他们的平等和散列方法来实现正确的,什么是测试两个字典平等的最简洁有效的方式?



在本上下文两个字典说是平等的,如果它们包含相同的一套钥匙(为了不重要),并为每一个这样的钥匙,他们同意的价值。



在这里有一些方法,我想出了(有可能还有更多):

 公共BOOL比较1< TKEY的,TValue>(
字典< TKEY的,TValue> DIC1,
字典< TKEY的,TValue> dic2)
{
返回dic1.OrderBy(X => x.Key)。
SequenceEqual(dic2.OrderBy(X => x.Key));
}

公共BOOL比较匹配< TKEY的,TValue>(
字典< TKEY的,TValue> DIC1,
字典< TKEY的,TValue> dic2)
{
回报率(dic1.Count == dic2.Count&放大器;&安培;
dic1.Intersect(dic2).Count之间的()
等于(dic1.Count));
}

公共BOOL Compare3< TKEY的,TValue>(
字典< TKEY的,TValue> DIC1,
字典< TKEY的,TValue> dic2)
{
回报率(dic1.Intersect(dic2).Count之间的()
等于(dic1.Union(dic2).Count之间的()));
}


解决方案

  dic1.Count == dic2.Count&放大器;&安培; !dic1.Except(dic2)。任何(); 


Assuming dictionary keys and values have their equals and hash methods implemented correctly, what is the most succinct and efficient way to test for equality of two dictionaries?

In this context two dictionaries are said to be equal if they contain the same set of keys (order not important), and for every such key, they agree on the value.

here are some ways i came up with (there are probably many more):

public bool Compare1<TKey, TValue>(
    Dictionary<TKey, TValue> dic1, 
    Dictionary<TKey,TValue> dic2)
{
    return dic1.OrderBy(x => x.Key).
        SequenceEqual(dic2.OrderBy(x => x.Key));
}

public bool Compare2<TKey, TValue>(
    Dictionary<TKey, TValue> dic1, 
    Dictionary<TKey, TValue> dic2)
{
    return (dic1.Count == dic2.Count && 
        dic1.Intersect(dic2).Count().
        Equals(dic1.Count));
}

public bool Compare3<TKey, TValue>(
    Dictionary<TKey, TValue> dic1, 
    Dictionary<TKey, TValue> dic2)
{
    return (dic1.Intersect(dic2).Count().
        Equals(dic1.Union(dic2).Count()));
}

解决方案

dic1.Count == dic2.Count && !dic1.Except(dic2).Any();

这篇关于在C#字典之间测试相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆