Posted by: Cirilo Meggiolaro | 11/25/2008

Tip of the day #42 – Custom comparer class

When you work with a generic List<T>, you may want to check if an object exists in the list before you add it.

If you just use the Contains method to check if the list has an instance of an object, you will have a value equals false if the instances are different even if both objects have the same properties values once you are testing the instances and not the values.

To implement a custom comparer to your classes you can use the IEqualityComparer<T> Interface.

How to…

Let’s use the following Product class for the example:

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal UnitPrice { get; set; }
}

Create a custom comparer class is straightforward if you are used to work with interfaces.

Here’s an example about how to create a custom comparer class based on the Product class. For this example, I am assuming that the check must be performed only by comparing the products ID’s:

public class ProductEqualityComparer : IEqualityComparer<Product>
{
    public bool Equals(Product x, Product y)
    {
        return (x.ID == y.ID);
    }

    public int GetHashCode(Product obj)
    {
        return obj.ID.GetHashCode();
    }

    bool IEqualityComparer<Product>.Equals(Product x, Product y)
    {
        return (x.ID == y.ID);
    }

    int IEqualityComparer<Product>.GetHashCode(Product obj)
    {
        return obj.ID.GetHashCode();
    }
}

To get more details about IEqualityComparer<T> interface, click here!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: