【问题标题】:How should I assert two collections' elements are identical?我应该如何断言两个集合的元素是相同的?
【发布时间】:2013-01-04 22:49:58
【问题描述】:

我应该如何断言两个集合包含相同的元素 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 中。 Assert 会更可取,因为它可能会提供更多关于它们有何不同的信息。

【问题讨论】:

    标签: c# unit-testing


    【解决方案1】:

    您可以使用CollectionAssert.AreEquivalent

    【讨论】:

      【解决方案2】:

      这是一种选择:

      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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-16
        • 2023-04-02
        相关资源
        最近更新 更多