Welcome to EMC Consulting Blogs Sign in | Join | Help

Simon Munro

Comparing Arrays with LINQ

I needed to compare the contents of two arrays to see if they were the same.  Obviously Equals won't work because they are different objects and although it would be easy enough to write a little routine to iterate through the arrays I thought that a) it must have been done before and b) there must be some better, generally accepted way of doing it in C#.

The methods suggested in various forums that I followed from a Google search looked a bit tacky and amateur.  I started scratching around MSDN and came across methods like 'union' and 'intersection'.  I though that since my arrays are essentially sets that there must be some way of doing a set difference on the arrays.  If the result of a set difference is empty then the arrays must be the same.

In the System.Linq namespace I found Except on Enumerable.  So you get useful methods like :

So my code to compare arrays looks like this...

string[] a = {"1", "2", "3"};

string[] b = { "1", "2", "3" };

IEnumerable<string> setResult1 = a.Except(b);

int i = setResult1.Count();

// i == 0

 

string[] c = { "1", "2" };

IEnumerable<string> setResult2 = a.Except(c);

int j = setResult2.Count();

// j == 1

I am sure that an iteration happens somewhere in the background, but using this method is simple, readable and maintainable.

Simon Munro

Published Thursday, October 23, 2008 9:41 AM by simon.munro
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Owain.Wragg said:

You could use the SequenceEqual extension method e.g.

           string[] a = { "1", "2", "3" };

           string[] b = { "1", "2", "3" };

           bool areEqual = a.SequenceEqual(b);

           //areEqual == true

           string[] c = { "1", "2", "4" };

           areEqual = a.SequenceEqual(c);

           //areEqual == false

The only thing to note is that if the arrays are in different orders SequenceEqual will return false, so if this matters you would need to sort the arrays first.

October 23, 2008 10:38 AM
 

simon.munro said:

Thanks Owain!  My blinkers only saw the set operators

October 23, 2008 11:11 AM

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server (Personal Edition), by Telligent Systems