日期:2014-05-17  浏览次数:20457 次

用linq查询怎么实现唯一distinct的查询效果
有下面的语句,
select distiinct name,pass, userid from users where name like '%z' order by userid desc;
怎么用LINQ来实现这种查询的效果?

------解决方案--------------------
初学者写一个,
var query= (from p in users 
where p.name.EndsWith("z")
group p by p.name into g
orderby p.userid descending
select new 

name=g.FirstOrDefault(),
pass=p.pass,
userid=p.userid 
};
------解决方案--------------------
C# code

 public class UserComparer : IEqualityComparer<User>  
    {  
        public bool Equals(User u1, User u2)  
        {  
            return u1.Name==u2.Name;  
        }  
        public int GetHashCode(User u)  
        {  
            return u.ToString().GetHashCode();  
        }  
    }  
var query=db.Users.Disctinct(new UserComparer());

------解决方案--------------------
C# code

public class UserComparer : IEqualityComparer<User>  
    {  
        public bool Equals(User u1, User u2)  
        {  
            return u1.Name==u2.Name;  
        }  
        public int GetHashCode(User u)  
        {  
            return u.ToString().GetHashCode();  
        }  
    }  
var query=db.Users.Where(u=>u.Name.EndWith("z"))
          .OrderByDescending(u=>u.userid)
          .Disctinct(new UserComparer());