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

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

    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.

提交回复
热议问题