C# Enumerable Distinct(IEnumerable, IEqualityComparer)

Description

Returns distinct elements from a sequence by using a specified IEqualityComparer to compare values.

Syntax


public static IEnumerable<TSource> Distinct<TSource>(
  this IEnumerable<TSource> source,
  IEqualityComparer<TSource> comparer
)

Parameters

  • TSource - The type of the elements of source.
  • source - The sequence to remove duplicate elements from.
  • comparer - An IEqualityComparer to compare values.

Returns

Returns distinct elements from a sequence by using a specified IEqualityComparer to compare values.

Example

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


//from   ww w  . j a  va 2 s.co  m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
    Product[] products = { new Product { Name = "apple", Code = 9 }, 
                           new Product { Name = "orange", Code = 4 }, 
                           new Product { Name = "apple", Code = 9 }, 
                           new Product { Name = "lemon", Code = 12 } };
    
    IEnumerable<Product> noduplicates =
        products.Distinct(new ProductComparer());
    
    foreach (var product in noduplicates)
        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