#423 – Compare Two Lists Using SequenceEquals
September 30, 2011 Leave a comment
If you use either the == operator or the Equals method of the List<T> type to compare two lists, the return value will be true only if you are comparing two references to the exact same List<T> instance. List<T> does not override either the == operator or the Equals method, so the comparison falls back to the reference equality check performed by Object.Equals.
List<int> myPrimes = new List<int> { 2, 3, 5, 7, 11, 13, 17 }; List<int> yourPrimes = new List<int> { 2, 3, 5, 7, 11, 13, 17 }; // == and Equals : reference equality bool compare = (myPrimes == yourPrimes); // false compare = myPrimes.Equals(yourPrimes); // false
If you want to compare two lists by comparing the values of the objects in the list, you can use the SequenceEqual method provide by System.Linq.
// SequenceEquals method : value equality compare = myPrimes.SequenceEqual(yourPrimes); // true List<int> dougsPrimes = new List<int> { 2, 3, 5, 7, 11, 13, 19 }; // oops compare = yourPrimes.SequenceEqual(dougsPrimes); // false