简体   繁体   中英

Equality between two enumerables

I have two enumerables with the exact same reference elements, and wondering why Equals wouldn't be true.

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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM