Other than stepping through the elements one by one, how do I compare two lists of strings for equality (in .NET 3.0):
This fails:
// Expected re
Using Linq and writing the code as an extension method :
public static bool EqualsOtherList<T>(this List<T> thisList, List<T> theOtherList)
{
if (thisList == null || theOtherList == null ||
thisList.Count != theOtherList.Count) return false;
return !thisList.Where((t, i) => !t.Equals(theOtherList[i])).Any();
}
I noticed no one actually told you why your original code didn't work. This is because the ==
operator in general tests reference equality (i.e. if the two instances are pointing to the same object in memory) unless the operator has been overloaded. List<T>
does not define an ==
operator so the base reference equals implementation is used.
As other posters have demonstrated, you will generally have to step through elements to test "collection equality." Of course, you should use the optimization suggested by user DreamWalker which first tests the Count of the collections before stepping through them.
Many test frameworks offer a CollectionAssert class:
CollectionAssert.AreEqual(expected, actual);
E.g MS Test