Search code examples
c#linqdistinct

Using Distinct with LINQ and Objects


Until recently, I was using a Distinct in LINQ to select a distinct category (an enum) from a table. This was working fine.

I now need to have it distinct on a class containing a category and country (both enums). The Distinct isn't working now.

What am I doing wrong?


Solution

  • I believe this post explains your problem: https://web.archive.org/web/20201203072646/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());