27

まったく同じ参照要素を持つ 2 つの列挙型があり、なぜ Equals が真にならないのか疑問に思っています。

副次的な質問として、各要素を比較する以下のコードは機能しますが、よりエレガントな方法が必要です

var other = (ActivityService) obj;
if (!AllAccounts.Count().Equals(other.AllAccounts.Count())) return false;
for (int i = 0; i < AllAccounts.Count(); i++) {
    if (!AllAccounts.ElementAt(i).Equals(other.AllAccounts.ElementAt(i))) {
        return false;
    }
}
return true;
4

2 に答える 2

49

Enumerable.SequenceEqual メソッドを見てください。

bool result = AllAccounts.SequenceEqual(other.AllAccounts);

データ型によっては、を受け入れるオーバーロードされたメソッドIEqualityComparerを使用してカスタム比較メソッドを定義する必要がある場合もあります。

于 2010-04-02T04:19:03.613 に答える
16

.Equals は、含まれる要素ではなく、列挙型の参照を比較しています。

于 2010-04-02T04:18:12.903 に答える