比较两个词典在C#中相等的数据? [英] Comparing two dictionaries for equal data in c#?

查看:246
本文介绍了比较两个词典在C#中相等的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一个字符串键,然后一个物体两本词典。该对象包含五个字段。有一种优雅的方式,以确保这两个词典首先包含相同的键,然后如果这是正确的,包含每个对象相同的五个领域?

I have two dictionaries containing a string key and then an object. The object contains five fields. Is there an elegant way to ensure both dictionaries first contain the same keys and then if this is correct, contain the same five fields per object?

请问两个字典具有相同的内置散列code什么的?

Would the two dictionaries have the same in-built hashcode or something?

编辑,不会出现奏效以下code:

EDIT, doesn't appear to be working for the following code:

Dictionary<string, MyClass> test1 = new Dictionary<string, MyClass>();
Dictionary<string, MyClass> test2 = new Dictionary<string, MyClass>();

MyClass i = new MyClass("", "", 1, 1, 1, 1);
MyClass j = new MyClass("", "", 1, 1, 1, 1);

test1.Add("1", i);
test2.Add("1", j);

bool equal = test1.OrderBy(r => r.Key).SequenceEqual(test2.OrderBy(r => r.Key));

class MyClass
{
    private string a;
    private string b;
    private long? c;
    private decimal d;
    private decimal e;
    private decimal f;

    public MyClass(string aa, string bb, long? cc, decimal dd, decimal ee, decimal ff)
    {
        a= aa;
        b= bb;
        c= cc;
        d= dd;
        e= ee;
        f= ff;
    }

这将返回错误的?

推荐答案

首先,你必须重写等于 GetHash code 类中的方法,否则比较将在引用上,而不是实际值进行。 (将code重写等于 GetHash code 在末尾提供) 的,在这之后,你可以使用:

First you have to override Equals and GetHashCode method in your class, otherwise comparison will be performed on references instead of actual values. (The code to override Equals and GetHashCode is provided at the end), after that you can use:

var result = (dic1 == dic2) || //Reference comparison (if both points to same object)
             (dic1.Count == dic2.Count && !dic1.Except(dic2).Any());

由于其中在字典中的物品退还在顺序是不确定的,你不能依靠的 Dictionary.SequenceEqual (不带排序依据的。

Since the order in which items in Dictionary are returned is undefined, you can not rely on Dictionary.SequenceEqual (without OrderBy).

您可以试试:

Dictionary<string, object> dic1 = new Dictionary<string, object>();
Dictionary<string, object> dic2 = new Dictionary<string, object>();
dic1.Add("Key1", new { Name = "abc", Number = "123", Address = "def", Loc = "xyz" });
dic1.Add("Key2", new { Name = "DEF", Number = "123", Address = "def", Loc = "xyz" });
dic1.Add("Key3", new { Name = "GHI", Number = "123", Address = "def", Loc = "xyz" });
dic1.Add("Key4", new { Name = "JKL", Number = "123", Address = "def", Loc = "xyz" });

dic2.Add("Key1",new { Name = "abc",Number=  "123", Address= "def", Loc="xyz"});
dic2.Add("Key2", new { Name = "DEF", Number = "123", Address = "def", Loc = "xyz" });
dic2.Add("Key3", new { Name = "GHI", Number = "123", Address = "def", Loc = "xyz" });
dic2.Add("Key4", new { Name = "JKL", Number = "123", Address = "def", Loc = "xyz" });


bool result = dic1.SequenceEqual(dic2); //Do not use that

的时间上面将返回,但我们不能真正依靠,由于无序的自然词典

Most of the time the above will return true, but one can't really rely on that due to unordered nature of Dictionary.

由于 SequenceEqual 将比较的顺序为好,因此依靠的只有 SequenceEqual 可能的错误的。你必须使用排序依据来订购这两种词典,然后使用 SequenceEqual 这样的:

Since SequenceEqual will compare the order as well, therefore relying on only SequenceEqual could be wrong. You have to use OrderBy to order both dictionaries and then use SequenceEqual like:

bool result2 = dic1.OrderBy(r=>r.Key).SequenceEqual(dic2.OrderBy(r=>r.Key));

不过,这将涉及多个迭代,一次订购,另用 SequenceEqual 比较每个元素。

$ C $下覆盖等于 GetHash code

Code for overriding Equals and GetHashCode

private class MyClass
{
    private string a;
    private string b;
    private long? c;
    private decimal d;
    private decimal e;
    private decimal f;

    public MyClass(string aa, string bb, long? cc, decimal dd, decimal ee, decimal ff)
    {
        a = aa;
        b = bb;
        c = cc;
        d = dd;
        e = ee;
        f = ff;
    }

    protected bool Equals(MyClass other)
    {
        return string.Equals(a, other.a) && string.Equals(b, other.b) && c == other.c && e == other.e && d == other.d && f == other.f;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((MyClass)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            var hashCode = (a != null ? a.GetHashCode() : 0);
            hashCode = (hashCode * 397) ^ (b != null ? b.GetHashCode() : 0);
            hashCode = (hashCode * 397) ^ c.GetHashCode();
            hashCode = (hashCode * 397) ^ e.GetHashCode();
            hashCode = (hashCode * 397) ^ d.GetHashCode();
            hashCode = (hashCode * 397) ^ f.GetHashCode();
            return hashCode;
        }
    }
}

您还可能会看到:<一href="http://stackoverflow.com/questions/9317582/correct-way-to-override-equals-and-gethash$c$c">Correct方法重写equals()和GetHash code()

这篇关于比较两个词典在C#中相等的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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