Comparing Collections Independent of Item Order

12 December 2006

The other day I was writing some unit tests and wanted to compare two collections in C# independent of the order of the elements. Surprisingly, I couldn't find any suitable implementations, neither in the .NET API nor on the web. I only found one blog entry that presents a solution to the problem. However, I preferred a simpler approach that would also work with generic collections, so I created a very simple and naive solution.

It works with generic collections and uses Comparer.Default to determine equality of contained elements. The asymptotic behavior of the method below is quadratic, which is why I previously called it naive.

Anyway, I think if you need a simple solution and don't have very stringent performance requirements (e.g. writing unit tests), the code below might help you.

bool Compare<T>(ICollection<T> one, ICollection<T> two) {
if (one == null || two == null) // special case
return one == two;

if (ReferenceEquals(one, two)) // same objects
return true;

if (one.Count != two.Count)
return false;

IList listOne = new List<T>(one);
IList listTwo = new List<T>(two);

// make sure that every object in one is also in two
for (int i = 0; i < listOne.Count; i++) {
object obj = listOne[i];
if (!listTwo.Contains(obj))
return false;

return true;