Cook Computing


September 11, 2011 Written by Charles Cook

Enumerable.SequenceEqual() is another useful Linq extension method when working with arrays, for example arrays of type byte[]:

byte[] passwordHash = GetPasswordHash(password, salt);
byte[] streamPasswordHash = stream.ReadBytes(32);
if (!passwordHash.SequenceEqual(streamPasswordHash))
  throw new Exception("Wrong password");

Though it's not going to be particularly efficient if it's not optimized for the array case, as is the case with the Mono implementation:

public static bool SequenceEqual<TSource> (this IEnumerable<TSource> first, 
  IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
    Check.FirstAndSecond (first, second);

    if (comparer == null)
        comparer = EqualityComparer<TSource>.Default;

    using (IEnumerator<TSource> first_enumerator = first.GetEnumerator (),
        second_enumerator = second.GetEnumerator ()) {

        while (first_enumerator.MoveNext ()) {
            if (!second_enumerator.MoveNext ())
                return false;

            if (!comparer.Equals (first_enumerator.Current, second_enumerator.Current))
                return false;

        return !second_enumerator.MoveNext ();

So if performance is important you'll have to write your own code.