#423 – 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 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
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: