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
Create a Dictionary "dict" and then for each member in the first collection, do dict[member]++;
Then, loop over the second collection in the same way, but for each member do dict[member]--.
At the end, loop over all of the members in the dictionary:
private bool SetEqual (List left, List right) {
if (left.Count != right.Count)
return false;
Dictionary dict = new Dictionary();
foreach (int member in left) {
if (dict.ContainsKey(member) == false)
dict[member] = 1;
else
dict[member]++;
}
foreach (int member in right) {
if (dict.ContainsKey(member) == false)
return false;
else
dict[member]--;
}
foreach (KeyValuePair kvp in dict) {
if (kvp.Value != 0)
return false;
}
return true;
}
Edit: As far as I can tell this is on the same order as the most efficient algorithm. This algorithm is O(N), assuming that the Dictionary uses O(1) lookups.