Comparing two List<string> for equality

Adam Kane picture Adam Kane · Oct 10, 2009 · Viewed 47.1k times · Source

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 );

Answer

JaredPar picture JaredPar · Oct 10, 2009

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