I would like to compare two collections (in C#), but I\'m not sure of the best way to implement this efficiently.
I\'ve read the other thread about Enumerable.Sequen
A simple and fairly efficient solution is to sort both collections and then compare them for equality:
bool equal = collection1.OrderBy(i => i).SequenceEqual(
collection2.OrderBy(i => i));
This algorithm is O(N*logN), while your solution above is O(N^2).
If the collections have certain properties, you may be able to implement a faster solution. For example, if both of your collections are hash sets, they cannot contain duplicates. Also, checking whether a hash set contains some element is very fast. In that case an algorithm similar to yours would likely be fastest.