[英]Equality between two enumerables
I have two enumerables with the exact same reference elements, and wondering why Equals wouldn't be true. 我有两个具有完全相同的参考元素的枚举,并想知道为什么Equals不是真的。
As a side question, the code below to compare each element works, but there must be a more elegant way 作为一个附带问题,下面的代码比较每个元素的工作原理,但必须有一个更优雅的方式
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;
Have a look at the Enumerable.SequenceEqual method . 看看Enumerable.SequenceEqual方法 。
bool result = AllAccounts.SequenceEqual(other.AllAccounts);
Depending on the data type you may also need to use the overloaded method that accepts an IEqualityComparer
to define a custom comparison method. 根据数据类型,您可能还需要使用接受
IEqualityComparer
的重载方法来定义自定义比较方法。
.Equals比较了枚举的引用,而不是它们包含的元素 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.