两个枚举之间的平等

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

看看Enumerable.SequenceEqual方法 。

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

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

.Equals比较了枚举的引用,而不是它们包含的元素