Equality between two IEnumerable<IEnumerable<int>&g

本文关键字:IEnumerable lt gt int two between Equality | 更新日期: 2023-09-27 18:17:32

我不认为SequenceEqual在两者之间工作,因为"中间"元素(IEnumerable<int>)没有使用SequenceEqual

oneThingy.SequenceEqual(twoThingy)

在中间元素不使用String.Join的情况下,是否有办法得到相等?

Equality between two IEnumerable<IEnumerable<int>&g

SequenceEqual测试使用Equals;要使用SequenceEquals,你需要自己实现它。尝试使用Zip运算符与序列相等。

// example
var first = Enumerable.Range(1, 10).Select(i => Enumerable.Range(1, i));
var second = Enumerable.Range(1, 10).Select(i => Enumerable.Range(1, i));
bool nestedSequencesEqual = 
    // test if each sequence index is equal        
    first.Zip(second, (f, s) => f.SequenceEqual(s))
    // ensure all like sequences are equal
    .All(b => b);
// returns true

+1 @BleuM937的答案
作为另一种方法,您可以使用SequenceEqual重载与相等比较器:

IEnumerable<IEnumerable<int>> one = new IEnumerable<int>[] { new int[] { 1 }, new int[] { 1, 2, 3 } };
IEnumerable<IEnumerable<int>> two = new IEnumerable<int>[] { new int[] { 1 }, new int[] { 1, 2, 3 } };
bool nestedSequencesEqual = one.SequenceEqual(two, new SequencesComparer<int>());
class SequencesComparer<T> : IEqualityComparer<IEnumerable<T>> {
    public bool Equals(IEnumerable<T> x, IEnumerable<T> y) {
        return x.SequenceEqual(y);
    }
    public int GetHashCode(IEnumerable<T> obj) {
        return obj.GetHashCode();
    }
}

下面的代码为我工作…

public class IntList : List<int>, IEquatable<IntList>
{
    public bool Equals(IntList other)
    {
        return this.SequenceEqual(other);
    }
}
void Main()
{
    List<IntList> list1 = new List<IntList>(2);
    List<IntList> list2 = new List<IntList>(2);
    var list11 = new IntList() {1, 2, 3};
    list1.Add(list11);
    var list21 = new IntList() {1, 2, 3};
    list2.Add(list21);

    var result = list1.SequenceEqual(list2);
    Console.WriteLine(result);
}

参考:http://msdn.microsoft.com/en-us/library/bb348567 (v = vs.100) . aspx