Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two List<string> for equality

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 ); 
like image 323
Adam Kane Avatar asked Oct 10 '09 03:10

Adam Kane


People also ask

How do you compare two string objects for their equality?

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.

How do I compare two lists of strings?

Use sort() method and == operator to compare lists The sorted list and the == operator are used to compare the list, element by element.

Can you use == when comparing strings?

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.

How do I compare two lists for equality in Python?

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.


2 Answers

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

like image 109
JaredPar Avatar answered Oct 10 '22 17:10

JaredPar


Many test frameworks offer a CollectionAssert class:

CollectionAssert.AreEqual(expected, actual); 

E.g MS Test

like image 31
dahlbyk Avatar answered Oct 10 '22 16:10

dahlbyk