Wednesday, September 24, 2008

SequenceEqual is my favorite new hammer

A common programming task that many people face is comparing 2 enumerations to determine if they are equal. Ideally you would like to be able to write code like the following:

if(arrayA == arrayB)
{
//Do Stuff Here...
}

However as you know, arrayA will never equal arrayB in the code above since they are completely different objects. What you really want to know is if the values contained in arrayA are the same as the values contained in arrayB. Well, the SequenceEqual() method provides a mechanisim to do just that.

The SequenceEqual() method enumerates the two source sequences in parallel and compares corresponding elements by using the default equality comparer for TSource.

Here is a quick example showing 2 equal arrays...

string[] arrayA = new string[]{"a","b","c","d"};
string[] arrayB = new string[]{"a","b","c","d"};
string[] arrayC = new string[]{"w","x","y","z"};

bool A_Equals_B = arrayA.SequenceEqual(arrayB); //returns true;
bool A_Equals_C = arrayA.SequenceEqual(arrayC); //returns false;

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home