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