Using C# LINQ - A Practical Overview

player_one
5,158 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

SequenceEqual() method

The SequenceEqual() method takes a second IEnumerable<T> sequence as a parameter, and performs a comparison, element-by-element, with the target (first) sequence. If the two sequences contain the same number of elements, and each element in the first sequence is equal to the corresponding element in the second sequence (using the default equality comparer) then SequenceEqual() returns true. Otherwise, false is returned.

It is interesting to note that this can be used to compare any two sequences! So, for example, a list and an array can be compared using this method. It can be quite handy sometimes. The only stipulation is that the data type of the two sequences, <T>, must be the same.

// returns true
bool isEqual1 = new[] { 1, 2, 3 }.SequenceEqual(new List<int> { 1, 2, 3 });

// returns false
bool isEqual2 = new List<int> { 1, 2, 3, 4 }.SequenceEqual(new[] { 1, 2, 3 });

// returns true
bool isEqual3 = new List<int> { 1, 2, 3, 4 }.Take(3).SequenceEqual(new[] { 1, 2, 3 });

// returns false
bool isEqual4 = new[] { 2, 1, 2 }.SequenceEqual(new[] { 1, 1, 2 });

// returns true
bool isEqual5 = new[] { 2, 1, 2 }.Skip(1).SequenceEqual(new[] { 1, 1, 2 }.Skip(1));

NOTE: There is also another form of SequenceEqual() that takes an IEqualityComparer<T> comparer parameter to use instead of the default equality comparer.

SequenceEqual() quiz

Which of the following would both compile correctly and return true?

Which statements would compile and return true?
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content