Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check two List<T> lists for equality in C#

There are many ways to do this but I feel like I've missed a function or something.

Obviously List == List will use Object.Equals() and return false.

If every element of the list is equal and present in the same location in the opposite list then I would consider them to be equal. I'm using value types, but a correctly implemented Data object should work in the same fashion (i.e I'm not looking for a shallow copied list, only that the value of each object within is the same).

I've tried searching and there are similar questions, but my question is an equality of every element, in an exact order.

like image 793
Spence Avatar asked May 18 '09 06:05

Spence


People also ask

How can I check if two lists are the same in C#?

To determine if two lists are equal, where frequency and relative order of the respective elements doesn't matter, use the Enumerable. All method. It returns true if every element of the source sequence satisfy the specified predicate; false, otherwise.


2 Answers

Enumerable.SequenceEqual<TSource>

MSDN

like image 117
leppie Avatar answered Sep 28 '22 00:09

leppie


Evil implementation is

if (List1.Count == List2.Count)
{
   for(int i = 0; i < List1.Count; i++)
   {
      if(List1[i] != List2[i])
      {
         return false;
      }
   }
   return true;
}
return false;
like image 39
Spence Avatar answered Sep 28 '22 00:09

Spence