首先你必须在你的类中重写Equals
和GetHashCode
方法,否则将在引用而不是实际值上进行比较。(要覆盖的代码Equals
并GetHashCode
在最后提供),之后您可以使用:
var result = (dic1 == dic2) || //Reference comparison (if both points to same object)
(dic1.Count == dic2.Count && !dic1.Except(dic2).Any());
由于返回 Dictionary 中的项目的顺序是未定义的,因此您不能依赖Dictionary.SequenceEqual (没有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
大多数情况下,上述内容会返回true
,但由于 的无序性质,不能真正依赖它Dictionary
。
由于SequenceEqual
也会比较顺序,所以只靠可能 SequenceEqual
是错误的。您必须使用OrderBy
来订购两个字典,然后使用SequenceEqual
如下:
bool result2 = dic1.OrderBy(r=>r.Key).SequenceEqual(dic2.OrderBy(r=>r.Key));
但这将涉及多次迭代,一次用于排序,另一次用于使用SequenceEqual
.
覆盖Equals
和代码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;
}
}
}
您可能还会看到:覆盖 Equals() 和 GetHashCode() 的正确方法