CSharp - LINQ SequenceEqual


The SequenceEqual operator determines whether two input sequences are equal.


There are two prototypes we cover.

public static bool SequenceEqual<T>(
  this IEnumerable<T> first,
  IEnumerable<T> second);

This operator compares the elements of each using the System.Object.Equals method.

If the elements are all equal and the sequences have the same number of elements, the operator returns true. Otherwise, it returns false.

The second prototype of the operator accepts IEqualityComparer<T> object to determine element equality.

public static bool SequenceEqual<T>(
  this IEnumerable<T> first,
  IEnumerable<T> second,
  IEqualityComparer<T> comparer);


ArgumentNullException is thrown if either argument is null.


using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from   ww  w  .j av  a  2  s .  c  o  m*/
    static void Main(string[] args)
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        bool eq = codeNames.SequenceEqual(codeNames);
        eq = codeNames.SequenceEqual(codeNames.Take(codeNames.Count()));
        eq = codeNames.SequenceEqual(codeNames.Take(codeNames.Count() - 1));


In the code above, we use the Take operator to take only the first N number of elements of the codeNames array.

Then compare that output sequence to the original codeNames sequence.

Related Topics