最初に、クラスでオーバーライド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 内のアイテムが返される順序は undefinedであるため、 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
ほとんどの場合、上記は を返しますがtrue
、 の順序付けられていない性質のために、実際にはそれに頼ることはできませんDictionary
。
順序も比較するので、それだけSequenceEqual
に頼るのは間違っている可能性があります。両方の辞書を注文してから、次のように使用する必要があります。 SequenceEqual
OrderBy
SequenceEqual
bool result2 = dic1.OrderBy(r=>r.Key).SequenceEqual(dic2.OrderBy(r=>r.Key));
ただし、これには複数の反復が含まれます。1 つは順序付けのため、もう 1 つは を使用して各要素を比較するため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() をオーバーライドする正しい方法