C# Enumerable Except(IEnumerable, IEnumerable, IEqualityComparer)

Description

Produces the set difference of two sequences by using the specified IEqualityComparer to compare values.

Syntax


public static IEnumerable<TSource> Except<TSource>(
  this IEnumerable<TSource> first,
  IEnumerable<TSource> second,//from w  ww .java2 s .  c  o m
  IEqualityComparer<TSource> comparer
)

Parameters

  • TSource - The type of the elements of the input sequences.
  • first - An IEnumerable whose elements that are not also in second will be returned.
  • second - An IEnumerable whose elements that also occur in the first sequence will cause those elements to be removed from the returned sequence.
  • comparer - An IEqualityComparer to compare values.

Example

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


//from  w  w w  . j  a v a 2  s  .  c  o  m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
        Product[] fruits1 = { new Product { Name = "apple", Code = 9 }, 
                               new Product { Name = "orange", Code = 4 },
                                new Product { Name = "lemon", Code = 12 } };

        Product[] fruits2 = { new Product { Name = "apple", Code = 9 } };

        IEnumerable<Product> except =
            fruits1.Except(fruits2, new ProductComparer());

        foreach (var product in except)
            Console.WriteLine(product.Name + " " + product.Code);

  }
}
    
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