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

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

    This simple solution forces the IEnumerable's generic type to implement IComparable. Because of OrderBy's definition.

    If you don't want to make such an assumption but still want use this solution, you can use the following piece of code :

    bool equal = collection1.OrderBy(i => i?.GetHashCode())
       .SequenceEqual(collection2.OrderBy(i => i?.GetHashCode()));
    
    0 讨论(0)
提交回复
热议问题