Using Distinct with LINQ and Objects

I believe this post explains your problem: http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx

The content of the above link can be summed up by saying that the Distinct() method can be replaced by doing the following.

var distinctItems = items
       .GroupBy(x => x.PropertyToCompare)
       .Select(x => x.First());

try an IQualityComparer

public class MyObjEqualityComparer : IEqualityComparer<MyObj>
{
    public bool Equals(MyObj x, MyObj y)
    {
        return x.Category.Equals(y.Category) &&
               x.Country.Equals(y.Country);
    }

    public int GetHashCode(MyObj obj)
    {
        return obj.GetHashCode();
    }
}

then use here

var comparer = new MyObjEqualityComparer();
myObjs.Where(m => m.SomeProperty == "whatever").Distinct(comparer);

Tags:

Linq

Distinct