How to Verify two Int Array and see if they are in a same order

时间:2016-09-01 06:13:59

标签: c#

I've my list below which gives value (1,2,3)

int[] myInts = x.Select(int.Parse).ToArray();

and i need to compare it to other list which is below,which is also (1,2,3)

var array = Enumerable.Range(1, 3).ToArray();

Now if i do

bool isEqual = Enumerable.SequenceEqual(myInts, array);

it is verifying my list and giving me True . But i want to make sure that myInts array will be in a same order then only it will pass . not like if those values are equal and can be in any order.

so how would i update my above code. Please let me know .

1 个答案:

答案 0 :(得分:5)

SequenceEqual checks for exactly that. A sequence is ordered, so for two sequences to be equal, they have to have the same number of items, and the same items, in the same order.

You can look at the source to verify that as well:

public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
    if (comparer == null) comparer = EqualityComparer<TSource>.Default;
    if (first == null) throw Error.ArgumentNull("first");
    if (second == null) throw Error.ArgumentNull("second");

    using (IEnumerator<TSource> e1 = first.GetEnumerator())
    using (IEnumerator<TSource> e2 = second.GetEnumerator())
    {
        while (e1.MoveNext())
        {
            if (!(e2.MoveNext() &&
                  comparer.Equals(e1.Current, e2.Current))) return false;
        }
        if (e2.MoveNext()) return false;
    }
    return true;
}

The loop breaks and the method returns false in case both have different numbers of items, or if any item isn't equal to the item at the same place in the other sequence.