gpt4 book ai didi

c# - LINQ 选择不同的 c#

转载 作者:太空狗 更新时间:2023-10-29 21:18:33 24 4
gpt4 key购买 nike

我正在尝试做一个不包含重复的 IdUser 值的查询,但不起作用。

这是我的 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

查询给出重复记录

为什么它不起作用?

最佳答案

我想你想使用 Distinct(IEqualityComparer<T>)重载。您需要创建一个 IEqualityComparer做你想做的事:

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

然后像这样使用它:

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,但很可能会得到您想要的结果。

关于c# - LINQ 选择不同的 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11673584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com