LINQ select distinct c#

前端 未结 3 968
悲哀的现实
悲哀的现实 2021-01-02 21:11

I\'m trying to do a query that does not include repeated IdUser values, ​​but does not work.

this is my linq query:

var         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-02 21:30

    When comparing class instances (vs. anonymous types) you need to define "equality". For anonymous types the compiler assumes that equality means "all fields are equal" like SQL does. So you have a few choices:

    1. Use an anonymous type in your query, use .Distinct(), and convert to a strong type afterwards,
    2. Define an IEqualityComparer class and pass that to Distinct,
    3. Override Equals (and GetHashCode) in Usuers

    2) and 3) will be very similar code. 2) is more flexible (you can define equality in different ways by defining different classes, while 3) will be used whenever you compare Uusers insatnces (not just in this query).

    See my answer to a similar problem here.

提交回复
热议问题