LINQ选择不同的C# [英] LINQ select distinct c#

查看:133
本文介绍了LINQ选择不同的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做,不包括重复 ID用户值的查询,但不起作用。

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

这是我的LINQ查询:

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



我想这样的:

SELECT   distinct CONSULT.IdUser , CONSULT.DateCreate, 
         CONSULT.IdTypeConsult , USER.Sex
FROM   CONSULT INNER JOIN
       USER ON CONSULT.IdUser = USER.IdUser 

查询放弃重复记录

为什么它不工作?

推荐答案

我想你想使用在分明(的IEqualityComparer< T>)超载。您需要创建一个的IEqualityComparer 做你想要什么:

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

class UserComparer : IEqualityComparer<UsuersViewModel >
{
    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);



我不知道是否会产生你想要的SQL,但可能会得到的结果你想要的。

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

这篇关于LINQ选择不同的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆