How to make Linq distinct work for you

Have you even tried using linq on your objects then wanted to a distinct but couldn’t ?, Heres why this does not happen, .net doesn’t know how to distinguish between two custome objects (even though this looks obvious in most of the cases), So what should we do ?

You have to exted the IEqualityComparer with a custom extension which would allow you to compare your custom objects

Though mine is simple, I am sure that you will make more use of this than me

    class Comparer : IEqualityComparer<GridDetails>
    {
        public bool Equals(GridDetails x, GridDetails y)
        {
            return x.Name == y.Name;
        }
 
        public int GetHashCode(GridDetails obj)
        {
            return obj.Name.GetHashCode();
        }
    }

An Example usage would be :

this.grid.DataSource = data.ToList().Distinct(new Aptra.Profile.BO.Comparer());
28
Nov 2008
Author naresh
Category

.net Programming

Comments 1 Comment
TAGS

,

One Response to “How to make Linq distinct work for you”

Leave a Reply