Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
like image 556
Berryl Avatar asked Apr 02 '10 04:04

Berryl


2 Answers

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.

like image 200
Ahmad Mageed Avatar answered Sep 30 '22 13:09

Ahmad Mageed


.Equals is comparing the references of the enumerables, not the elements they contain.

like image 45
Anthony Pegram Avatar answered Sep 30 '22 12:09

Anthony Pegram