Partager via


Enumerable.SequenceEqual<TSource> Method (IEnumerable<TSource>, IEnumerable<TSource>)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

Namespace:  System.Linq
Assembly:  System.Core (in System.Core.dll)

Syntax

'Declaration
<ExtensionAttribute> _
Public Shared Function SequenceEqual(Of TSource) ( _
    first As IEnumerable(Of TSource), _
    second As IEnumerable(Of TSource) _
) As Boolean
public static bool SequenceEqual<TSource>(
    this IEnumerable<TSource> first,
    IEnumerable<TSource> second
)

Type Parameters

  • TSource
    The type of the elements of the input sequences.

Parameters

Return Value

Type: System.Boolean
true if the two source sequences are of equal length and their corresponding elements are equal according to the default equality comparer for their type; otherwise, false.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type IEnumerable<TSource>. When you use instance method syntax to call this method, omit the first parameter.

Exceptions

Exception Condition
ArgumentNullException

first or second is nulla null reference (Nothing in Visual Basic).

Remarks

The SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method enumerates the two source sequences in parallel and compares corresponding elements by using the default equality comparer for TSource, Default. The default equality comparer, Default, is used to compare values of the types that implement the IEqualityComparer<T> generic interface. To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type.

Examples

The following code examples demonstrate how to use SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) to determine whether two sequences are equal. In the first two examples, the method determines whether the compared sequences contain references to the same objects. In the third and fourth examples, the method compares the actual data of the objects within the sequences.

In this example the sequences are equal.

   Class Pet
      Public Name As String
      Public Age As Integer
   End Class

   Sub SequenceEqualEx1()
      ' Create two Pet objects.
      Dim pet1 As New Pet With {.Name = "Turbo", .Age = 2}
      Dim pet2 As New Pet With {.Name = "Peanut", .Age = 8}

      ' Create two lists of pets.
      Dim pets1 As New List(Of Pet)(New Pet() {pet1, pet2})
      Dim pets2 As New List(Of Pet)(New Pet() {pet1, pet2})

      'Determine if the two lists are equal.
      Dim equal As Boolean = pets1.SequenceEqual(pets2)

      ' Display the output.
      Dim text As String = IIf(equal, "are", "are not")
      outputBlock.Text &= "The lists " & text & " equal." & vbCrLf

   End Sub

   ' This code produces the following output:
   '
   ' The lists are equal.

      class Pet
      {
         public string Name { get; set; }
         public int Age { get; set; }
      }

      public static void SequenceEqualEx1()
      {
         Pet pet1 = new Pet { Name = "Turbo", Age = 2 };
         Pet pet2 = new Pet { Name = "Peanut", Age = 8 };

         // Create two lists of pets.
         List<Pet> pets1 = new List<Pet> { pet1, pet2 };
         List<Pet> pets2 = new List<Pet> { pet1, pet2 };

         bool equal = pets1.SequenceEqual(pets2);

         outputBlock.Text += String.Format(
             "The lists {0} equal.",
             equal ? "are" : "are not") + "\n";
      }

      /*
       This code produces the following output:

       The lists are equal.
      */

The following code example compares two sequences that are not equal. Note that the sequences contain identical data, but because the objects that they contain have different references, the sequences are not considered equal.

      ' Create two Pet objects.
      Dim pet1 As New Pet With {.Name = "Turbo", .Age = 2}
      Dim pet2 As New Pet With {.Name = "Peanut", .Age = 8}

      ' Create two lists of pets.
      Dim pets1 As New List(Of Pet)()
      pets1.Add(pet1)
      pets1.Add(pet2)

      Dim pets2 As New List(Of Pet)()
      pets2.Add(New Pet With {.Name = "Turbo", .Age = 2})
      pets2.Add(New Pet With {.Name = "Peanut", .Age = 8})

      ' Determine if the two lists are equal.
      Dim equal As Boolean = pets1.SequenceEqual(pets2)

      ' Display the output.
      Dim text As String = IIf(equal, "are", "are not")
      outputBlock.Text &= "The lists " & text & " equal." & vbCrLf

      ' This code produces the following output:
      '
      ' The lists are not equal.

      class Pet
      {
         public string Name { get; set; }
         public int Age { get; set; }
      }

      public static void SequenceEqualEx2()
      {
         Pet pet1 = new Pet() { Name = "Turbo", Age = 2 };
         Pet pet2 = new Pet() { Name = "Peanut", Age = 8 };

         // Create two lists of pets.
         List<Pet> pets1 = new List<Pet> { pet1, pet2 };
         List<Pet> pets2 =
             new List<Pet> { new Pet { Name = "Turbo", Age = 2 }, 
                                 new Pet { Name = "Peanut", Age = 8 } };

         bool equal = pets1.SequenceEqual(pets2);

         outputBlock.Text += String.Format("The lists {0} equal.", equal ? "are" : "are not") + "\n";
      }

      /*
       This code produces the following output:

       The lists are not equal.
      */

If you want to compare the actual data of the objects in the sequences instead of just comparing their references, you have to implement the IEqualityComparer<T> generic interface in your class. The following code example shows how to implement this interface in a custom data type and provide GetHashCode and Equals methods.

Public Class Product
    Implements IEquatable(Of Product)

    Public Property Name As String
    Public Property Code As Integer

    Public Function Equals1(
        ByVal other As Product
        ) As Boolean Implements IEquatable(Of Product).Equals

        ' Check whether the compared object is null.
        If other Is Nothing Then Return False

        ' Check whether the compared object references the same data.
        If Me Is Other Then Return True

        ' Check whether the products' properties are equal.
        Return Code.Equals(other.Code) AndAlso Name.Equals(other.Name)
    End Function

    Public Overrides Function GetHashCode() As Integer

        ' Get hash code for the Name field if it is not null.
        Dim hashProductName = If(Name Is Nothing, 0, Name.GetHashCode())

        ' Get hash code for the Code field.
        Dim hashProductCode = Code.GetHashCode()

        ' Calculate the hash code for the product.
        Return hashProductName Xor hashProductCode
    End Function
End Class

public class Product : IEquatable<Product>
{
    public string Name { get; set; }
    public int Code { get; set; }

    public bool Equals(Product other)
    {

        //Check whether the compared object is null.
        if (Object.ReferenceEquals(other, null)) return false;

        //Check whether the compared object references the same data.
        if (Object.ReferenceEquals(this, other)) return true;

        //Check whether the products' properties are equal.
        return Code.Equals(other.Code) && Name.Equals(other.Name);
    }

    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects.

    public override int GetHashCode()
    {

        //Get hash code for the Name field if it is not null.
        int hashProductName = Name == null ? 0 : Name.GetHashCode();

        //Get hash code for the Code field.
        int hashProductCode = Code.GetHashCode();

        //Calculate the hash code for the product.
        return hashProductName ^ hashProductCode;
    }
}

After you implement this interface, you can use sequences of Product objects in the SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method, as shown in the following example.


Dim storeA() As Product = 
    {New Product With {.Name = "apple", .Code = 9}, 
     New Product With {.Name = "orange", .Code = 4}}

Dim storeB() As Product = 
    {New Product With {.Name = "apple", .Code = 9}, 
     New Product With {.Name = "orange", .Code = 4}}

Dim equalAB = storeA.SequenceEqual(storeB)

outputBlock.Text &= "Equal? " & equalAB & vbCrLf

' This code produces the following output:

' Equal? True

        Product[] storeA = { new Product { Name = "apple", Code = 9 }, 
                               new Product { Name = "orange", Code = 4 } };

        Product[] storeB = { new Product { Name = "apple", Code = 9 }, 
                               new Product { Name = "orange", Code = 4 } };

        bool equalAB = storeA.SequenceEqual(storeB);

        outputBlock.Text += "Equal? " + equalAB + "\n";

        /*
            This code produces the following output:

            Equal? True
        */

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.