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 result. List<string> expected = new List<string>(); expected.Add( "a" ); expected.Add( "b" ); expected.Add( "c" ); // Actual result actual = new List<string>(); actual.Add( "a" ); actual.Add( "b" ); actual.Add( "c" ); // Verdict Assert.IsTrue( actual == expected );
It compares values of string for equality. String class provides the following two methods: public boolean equals(Object another) compares this string to the specified object. public boolean equalsIgnoreCase(String another) compares this string to another string, ignoring case.
Use sort() method and == operator to compare lists The sorted list and the == operator are used to compare the list, element by element.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
sort() and == operator. The list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.
Try the following
var equal = expected.SequenceEqual(actual);
Test Version
Assert.IsTrue( actual.SequenceEqual(expected) );
The SequenceEqual extension method will compare the elements of the collection in order for equality.
See http://msdn.microsoft.com/en-us/library/bb348567(v=vs.100).aspx
Many test frameworks offer a CollectionAssert class:
CollectionAssert.AreEqual(expected, actual);
E.g MS Test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With