Compare Two Lists Using SequenceEquals

If you use either the == operator or the Equals method of the List<T> type to compare two lists, the return value will betrue 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 byObject.Equals.
1
2
3
4
5
6
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 SequenceEqualmethod provide by System.Linq.


1
2
3
4
5
// 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