Back
Close

Using C# LINQ - A Practical Overview

player_one
69.2K views
Previous: Any and All Next: Aggregate

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?
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants