27

我有两个具有完全相同参考元素的枚举,并且想知道为什么 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);

根据数据类型,您可能还需要使用接受 an的重载方法IEqualityComparer来定义自定义比较方法。

于 2010-04-02T04:19:03.613 回答
16

.Equals 是比较enumerables的引用,而不是它们包含的元素。

于 2010-04-02T04:18:12.903 回答