Comparing two collections for equality irrespective of the order of items in them

后端 未结 19 1603
我在风中等你
我在风中等你 2020-11-22 10:28

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

19条回答
  •  长情又很酷
    2020-11-22 11:12

    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.

提交回复
热议问题