Enumerable.SequenceEqual

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

Description

Determines whether two sequences are equal by comparing the elements by using the default equality comparer for each element's type.

Two sequences are equal if they have the same number of elements and all corresponding elements in the two sequences are equal.

Parameters

  • first

    An IEnumerable<TSource> to compare with the second enumerable collection.

  • second

    An IEnumerable<TSource> to compare with the first enumerable collection.

  • comparer

    (Optional) An IEqualityComparer<TSource> to use to compare elements. If null, the default equality comparer for the element type is used.

Returns

true if the two sequences are equal; otherwise, false.

Remarks

  • If both sequences are empty, the method returns true.
  • If first is null, this method throws an ArgumentNullException.
  • If second is null, this method throws an ArgumentNullException.
  • The TSource type parameter is the type of the elements of the input sequences.

Examples


// Example 1: Comparing two identical integer arrays
int[] array1 = { 1, 2, 3 };
int[] array2 = { 1, 2, 3 };

bool areEqual = array1.SequenceEqual(array2); // areEqual will be true

Console.WriteLine($"Arrays are equal: {areEqual}");

// Example 2: Comparing two different integer arrays
int[] array3 = { 1, 2, 4 };
bool areDifferent = array1.SequenceEqual(array3); // areDifferent will be false

Console.WriteLine($"Arrays are different: {areDifferent}");

// Example 3: Comparing with a custom comparer (case-insensitive string comparison)
string[] names1 = { "Alice", "Bob", "Charlie" };
string[] names2 = { "alice", "bob", "charlie" };

bool areSameCaseInsensitive = names1.SequenceEqual(names2, StringComparer.OrdinalIgnoreCase); // true

Console.WriteLine($"String arrays are equal (case-insensitive): {areSameCaseInsensitive}");

// Example 4: Comparing sequences with different lengths
int[] array4 = { 1, 2 };
bool differentLength = array1.SequenceEqual(array4); // false

Console.WriteLine($"Arrays of different lengths are equal: {differentLength}");
                

See Also