Collection equality regardless of item order
3 12 2004I wanted 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.IsTrue(Collection.Equals(charsA, charsB, false));
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.IsTrue(Collection.Equals(intA, intB, false));
ArrayList arrayListA = new ArrayList();
ArrayList arrayListB = new ArrayList();
arrayListA.Add(charsA); // Adds the array as an item
arrayListB.AddRange(charsB); // Adds the items from the array
arrayListA.Add(intA);
arrayListB.AddRange(intB);
Assert.IsTrue(arrayListA.Count == 2);
Assert.IsTrue(arrayListB.Count == 20);
Assert.IsTrue(Collection.Equals(arrayListA, arrayListB, false));
I had to create the RelaxComparer so I could add all types to two SortedList collections that are built by the algorithm to determine equality. The SortedList objects are also used to keep track of the number of times each item appears in each collection.
I merged the CollectionEquals method I created earlier together with this new algorithm to a new Collection class that can test both types of collection equality:
Categories : .NET, c#






