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.
Evil implementation is
One can write a general purpose
IEqualityComparer<T>
for sequences. A simple one:A more fleshed out version: which should be better performing.
This has a few features:
The comparison is done from bottom to top. There is more probability for collections differing at the end in typical use-cases.
An
IEqualityComparer<T>
can be passed to base the comparison for items in the collection.MSDN
I knocked up a quick extension method:
Use linq
SequenceEqual
to check for sequence equality because Equals method checks for reference equality.The
SequenceEqual()
method takes a second IEnumerable<T>
sequence as a parameter, and performs a comparison, element-by-element, with the target (first) sequence. If the two sequences contain the same number of elements, and each element in the first sequence is equal to the corresponding element in the second sequence (using the default equality comparer) thenSequenceEqual()
returns true
. Otherwise,false
is returned.Or if you don't care about elements order use
Enumerable.All
method:The second version also requires another check for Count because it would return true even if
list2
contains more elements thanlist1
.I put together this variation:
The nerd in me also crawled out so I did a performance test against SequenceEquals, and this one has a slight edge.
Now, the question to ask; is this tiny, almost measurable performance gain worth adding the code to the code base and maintaining it? I very much doubt it ;o)