代码之家  ›  专栏  ›  技术社区  ›  CubanX

有LINQ等效方法吗?

  •  6
  • CubanX  · 技术社区  · 14 年前

    我知道林克有一个 SequenceEquals

    我要找的是一种更“等价”的功能类型。只是这两个序列包含相同的项目,不一定在同一顺序。

    例如,nUnit CollectionAssert.AreEqual() CollectionAssert.AreEquivalent() 照我说的做。

    我知道我可以通过以下两种方式来实现:

    1. 提前排序列表并使用 序列等于
    2. 使用 Intersect ,然后查看交点是否等于原始序列。

    var source = new[] {5, 6, 7};
    source.Intersect(new[] {5, 7, 6}).Count() == source.Length;
    
    3 回复  |  直到 10 年前
        1
  •  8
  •   Toby    14 年前

        2
  •  10
  •   Jon Skeet    14 年前

    你可以建立一个集合然后使用 HashSet<T>.SetEquals

    public static bool SetEquals<T>(this IEnumerable<T> source, IEnumerable<T> other)
    {
        HashSet<T> hashSet = new HashSet<T>(source);
        return hashSet.SetEquals(other); // Doesn't recurse! Calls HashSet.SetEquals
    }
    

    编辑:如注释中所述,这忽略了元素出现的次数,以及顺序-so { 1, 2 } { 1, 2, 1, 2, 1, 1, 1 } . 如果那不是你想要的,事情会变得更复杂一点。

        3
  •  2
  •   BartoszKP    10 年前

    public static bool SetEquivalent<T>(
        this IEnumerable<T> aSet,
        IEnumerable<T> anotherSet)
    {
        var diffA = aSet.Except(anotherSet).Count();
        var diffB = anotherSet.Except(aSet).Count();
        return diffA == diffB && diffA == 0;
    }