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

后端 未结 19 1895
我在风中等你
我在风中等你 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 10:57

    static bool SetsContainSameElements(IEnumerable set1, IEnumerable set2) {
        var setXOR = new HashSet(set1);
        setXOR.SymmetricExceptWith(set2);
        return (setXOR.Count == 0);
    }
    

    Solution requires .NET 3.5 and the System.Collections.Generic namespace. According to Microsoft, SymmetricExceptWith is an O(n + m) operation, with n representing the number of elements in the first set and m representing the number of elements in the second. You could always add an equality comparer to this function if necessary.

提交回复
热议问题