C# Enumerable SequenceEqual(IEnumerable, IEnumerable, IEqualityComparer)

Description

Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer.

Syntax


public static bool SequenceEqual<TSource>(
  this IEnumerable<TSource> first,
  IEnumerable<TSource> second,//from w  w w. j a  v  a 2 s  . c om
  IEqualityComparer<TSource> comparer
)

Parameters

  • TSource - The type of the elements of the input sequences.
  • first - An IEnumerable to compare to second.
  • second - An IEnumerable to compare to the first sequence.
  • comparer - An IEqualityComparer to use to compare elements.

Returns

Returns true if the two source sequences are of equal length and their corresponding elements compare equal according to comparer; otherwise, false.

Example

The following example shows how to implement an equality comparer that can be used in the SequenceEqual method.


//  ww  w.j  av  a2  s  .  c o m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
        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, new ProductComparer());

        Console.WriteLine("Equal? " + equalAB);


  }
}
    
public class Product
{
    public string Name { get; set; }
    public int Code { get; set; }
}
class ProductComparer : IEqualityComparer<Product>
{
    public bool Equals(Product x, Product y)
    {
        return x.Name == y.Name;
    }
    public int GetHashCode(Product product)
    {
        return product.Name.GetHashCode();
    }

}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable