LINQ select distinct c#

前端 未结 3 969
悲哀的现实
悲哀的现实 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:43

    I think you want to use the Distinct(IEqualityComparer) overload. You need to create an IEqualityComparer to do what you want:

    class UserComparer : IEqualityComparer
    {
        public bool Equals(UsuersViewModel  x, UsuersViewModel y)
        {
            //Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y)) return true;
    
            //Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;
    
            return x.IdUser == y.IdUser;
        }
    
        // If Equals() returns true for a pair of objects 
        // then GetHashCode() must return the same value for these objects.
    
        public int GetHashCode(UsuersViewModel  user)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(user, null)) return 0;
    
            return user.IdUser == null ? 0 : user.IdUser.GetHashCode();
        }
    }
    

    Then use it like this:

    var comparer = new UserComparer();
    var sql= (from u in db.USER
              join c in db.CONSULT on u.IdUser equals c.IdUser 
              select new UsuersViewModel 
                     {  
                        IdUser = c.IdUser, 
                        DateCreate=c.DateCreate, 
                        IdTypeConsult = c.IdTypeConsult, 
                        Sex=u.Sex 
                     })
                     .Distinct(comparer);
    

    I'm not sure if that will generate the SQL you want, but will likely get the results you want.

提交回复
热议问题