简体   繁体   中英

Equality between two IEnumerable<IEnumerable<int>> objects

I don't think SequenceEqual is working between the two because the "middle" elements ( IEnumerable<int> ) aren't using SequenceEqual .

oneThingy.SequenceEqual(twoThingy)

Short of using String.Join on the middle elements, is there a way to get equality?

SequenceEqual tests using Equals ; to use SequenceEquals you'll need to implement it yourself. Try using the Zip operator with sequence equals.

// 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 for @BleuM937 answer.
As an another approach you can use the SequenceEqual overloads with equality comparer:

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

The following code works for me...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM