Using Distinct with LINQ and Objects

后端 未结 5 1392
余生分开走
余生分开走 2021-01-03 23:20

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

5条回答
  •  别那么骄傲
    2021-01-03 23:29

    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());
    

提交回复
热议问题