我如何断言两个集合的元素是相同的?

时间:2013-01-21 19:52:43

标签: c# unit-testing

我如何断言两个集合包含相同的元素,而id顺序无关紧要?

这意味着两个集合中每个元素的数量是相同的。以下是一些例子:

等于:
1,2,3,4 == 1,2,3,4
1,2,3,4 == 4,2,3,1
2,1,2 == 2,2,1
1,2,2 == 2,2,1

不等于:
1!= 1,1
1,1,2!= 1,2,2

是否有一些罐装功能可以满足我的需求?我假设这将在Microsoft.VisualStudio.QualityTools.UnitTestFramework.Assert或LINQ中。断言是可取的,因为它可能会提供更多关于它们如何不同的信息。

2 个答案:

答案 0 :(得分:10)

您可以使用CollectionAssert.AreEquivalent

答案 1 :(得分:0)

这是一个选项:

public static bool AreEqual<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
    var dictionary = first.GroupBy(x => x)
        .ToDictionary(group => group.Key,
        group => group.Count());

    foreach (var item in second)
    {
        int count = dictionary[item];
        if (count <= 0)
            return false;
        else dictionary[item] = count - 1;
    }

    return dictionary.Values.All(count => count > 0);
}