Is there an easy way in xunit.net to compare two collections without regarding the items' order?

后端 未结 5 525
借酒劲吻你
借酒劲吻你 2021-01-01 11:08

In one of my tests, I want to ensure that a collection has certain items. Therefore, I want to compare this collection with the items of an expected collection not r

5条回答
  •  一向
    一向 (楼主)
    2021-01-01 11:37

    Maybe another way is:

    Assert.True(expected.SequenceEqual(actual));
    

    This does checks the order too. This is what happens internally:

    using (IEnumerator e1 = first.GetEnumerator())
    using (IEnumerator e2 = second.GetEnumerator())
    {
        while (e1.MoveNext())
        {
            if (!(e2.MoveNext() && comparer.Equals(e1.Current, e2.Current))) return false;
        }
        if (e2.MoveNext()) return false;
    }
    return true;
    

    So if you don't care about the order, just order both lists before:

    Assert.True(expected.OrderBy(i => i).SequenceEqual(actual.OrderBy(i => i)));
    

提交回复
热议问题