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

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

    If you use Shouldly, you can use ShouldAllBe with Contains.

    collection1 = {1, 2, 3, 4};
    collection2 = {2, 4, 1, 3};
    
    collection1.ShouldAllBe(item=>collection2.Contains(item)); // true
    

    And finally, you can write an extension.

    public static class ShouldlyIEnumerableExtensions
    {
        public static void ShouldEquivalentTo(this IEnumerable list, IEnumerable equivalent)
        {
            list.ShouldAllBe(l => equivalent.Contains(l));
        }
    }
    

    UPDATE

    A optional parameter exists on ShouldBe method.

    collection1.ShouldBe(collection2, ignoreOrder: true); // true
    

提交回复
热议问题