System Namespace
Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.
In C#:
public static bool SequenceEquals<T>(IEnumerable<T> first, IEnumerable<T> second);
In Visual Basic:
Public Shared Function SequenceEquals(Of T)(first As IEnumerable(Of T), second As IEnumerable(Of T)) As Boolean
T: The type of the elements in the sequences.first: An IEnumerable<T> to compare with the second sequence.second: An IEnumerable<T> to compare with the first sequence.true if the two sequences are equal; otherwise, false.Two sequences are considered equal if they are of the same length and if the elements at each corresponding position in the two sequences are equal.
This method uses the default equality comparer to compare elements. For a comparer that you specify, use the SequenceEquals<T>(IEnumerable<T>, IEnumerable<T>, IEqualityComparer<T>) overload.
| Type | Condition |
|---|---|
ArgumentNullException |
first or second is null. |
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<int> numbers1 = new List<int>() { 1, 2, 3 };
List<int> numbers2 = new List<int>() { 1, 2, 3 };
List<int> numbers3 = new List<int>() { 1, 2, 4 };
List<int> numbers4 = new List<int>() { 1, 2 };
bool isEqual12 = numbers1.SequenceEqual(numbers2); // Using extension method
bool isEqual13 = System.Linq.Enumerable.SequenceEqual(numbers1, numbers3); // Using static method
bool isEqual14 = numbers1.SequenceEqual(numbers4);
Console.WriteLine($"Sequence 1 and Sequence 2 are equal: {isEqual12}"); // Output: True
Console.WriteLine($"Sequence 1 and Sequence 3 are equal: {isEqual13}"); // Output: False
Console.WriteLine($"Sequence 1 and Sequence 4 are equal: {isEqual14}"); // Output: False
}
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Module Module1
Public Sub Main()
Dim numbers1 As New List(Of Integer)() From {1, 2, 3}
Dim numbers2 As New List(Of Integer)() From {1, 2, 3}
Dim numbers3 As New List(Of Integer)() From {1, 2, 4}
Dim numbers4 As New List(Of Integer)() From {1, 2}
Dim isEqual12 As Boolean = numbers1.SequenceEqual(numbers2) ' Using extension method
Dim isEqual13 As Boolean = System.Linq.Enumerable.SequenceEqual(numbers1, numbers3) ' Using static method
Dim isEqual14 As Boolean = numbers1.SequenceEqual(numbers4)
Console.WriteLine($"Sequence 1 and Sequence 2 are equal: {isEqual12}") ' Output: True
Console.WriteLine($"Sequence 1 and Sequence 3 are equal: {isEqual13}") ' Output: False
Console.WriteLine($"Sequence 1 and Sequence 4 are equal: {isEqual14}") ' Output: False
End Sub
End Module