Skip to main content
  1. Posts/

Collection equality regardless of item order

··1 min

I had a need to test collection equality disregarding order. One int array of 1,2,3,4 and another of 4,2,3,1 would be equal. Also, collections of collections would be compared only by their items and the number of times those items appear in any collection.

char[] charsA = new char[] { 'a', 'b', 'c', 'a' };
char[] charsB = new char[] { 'a', 'c', 'b', 'a' };

Assert.IsFalse(charsA.SequenceEqual(charsB));

int[] intA = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
               0, 1, 2, 3, 4, 5 };
int[] intB = new int[] { 9, 8, 7, 6, 5, 5, 4, 4, 3, 3,
               2, 2, 1, 1, 0, 0 };

Assert.IsFalse(intA.SequenceEqual(intB));
In .NET Framework 3.5 (released 2007), SequenceEqual and OrderBy were introduced.

Adding a sort, these sequence equality checks are now true:

Assert.IsTrue(charsA.OrderBy(c => c).SequenceEqual(
    charsB.OrderBy(c => c)));

Assert.IsTrue(intA.OrderBy(i => i).SequenceEqual(
    intB.OrderBy(i => i)));
George Tsiokos
Author
George Tsiokos

Comments

Interesting… I am not sure if, after reading this, I am falling in love with C# or simply deciding not to mingle with it :-) Keep them coming George!
Very Cool! A must for comparing collections!

Leave a comment

Preview

Comments are reviewed before publishing.