EqualityComparer Builder

Tango.Linq.EqualityComparerBuilder<T>

This class implements IEqualityComparer<T> interface and provides a method that can be used to create concrete objects that implements this comparison interface.

You can use this builder to define a dynamic comparison between two objects, you can inform this comparer as parameter for Distinct method from System.Linq namespace.

It's a better option than implements interface directly in class that you want to compare, because you can define multiple ways to compare same object types.

Properties

Name Type Description
Comparer Func<T, T, bool> Method used by Equals interface method.
HashCodeGetter Func<T, int> Method used by GetHashCode interface method.

Methods

Name Parameter Returns Description
Create Func<T, T, bool> comparer

Func<T, int> hashCodeGetter

EqualityComparerBuilder<T> Creates a new object that implements IEqualityComparer<T>.
Equals T x

T y

bool IEqualityComparer<T> interface method.
GetHashCode T obj int IEqualityComparer<T> interface method.

Usage

You can use the static method Create to creates a new instance of a comparer object.

See the code:

class Product
{
   public int Id { get; set; }
   public string Description { get; set; }
}

Func<Product, Product, bool> compareProducts = 
      (product1, product2) => product1.Id == product2.Id;

Func<Product, int> getHashCodeProduct =
      product => product.Id.GetHashCode();

var comparer = 
    EqualityComparerBuilder<Product>.Create(
        compareProducts, 
        getHashCodeProduct);

IEnumerable<Product> products = GetProducts();
products.Distinct(comparer);

In the previous example, the Distinct method will no longer comparer the object referece. The comparison will be made by comparisons of comparer object.

You can use anonymous methods directly as Create method parameters:

class Product
{
   public int Id { get; set; }
   public string Description { get; set; }
}
IEnumerable<Product> products = GetProducts();
products.Distinct(
    EqualityComparerBuilder<Product>.Create(
            (product1, product2) => product1.Id == product2.Id, 
            product => product.Id.GetHashCode());
);

results matching ""

    No results matching ""