如果我理解得很好,它应该是:
IEnumerable<User> z =
(from users in listOfUsersForReviewer
join roleUserLinks in context.RoleUserLinks
on users.UserID equals roleUserLinks.UserID into roleUserLinksJoin
// left join
from roleUserLinks in roleUserLinksJoin.DefaultIfEmpty()
where
(roleUserLinks == null
|| roleUserLinks.LinkStatusID == (byte)Enums.LinkStatus.Deleted)
&& !roleUserLinksJoin.Where(x=> roleUserLinks.LinkStatusID == (byte)Enums.LinkStatus.Added && x.UserID == roleUserLinks.UserID).Any()
select users).Distinct();
我添加了这个子查询:
&& !roleUserLinksJoin.Where(x=> roleUserLinks.LinkStatusID == (byte)Enums.LinkStatus.Added && x.UserID == roleUserLinks.UserID).Any()
它将从结果中删除不需要的行,其中包含有记录的RoleUserLinks
用户LinkStatusId
Added
。
我也将其更改roleUserLinks.LinkStatus == null
为roleUserLinks == null
避免NullReferenceException
在没有匹配的情况RoleUserLink
下User
我测试代码的示例代码
static void Main(string[] args)
{
var usersList = new List<User>()
{
new User() {UserID = 1},
new User() {UserID = 2},
new User() {UserID = 3}
};
var userLinksList = new List<RoleUserLink>()
{
new RoleUserLink() {UserID = 1, State = "del"},
new RoleUserLink() {UserID = 2, State = "add"},
new RoleUserLink() {UserID = 2, State = "del"}
};
IEnumerable<User> z = (from users in usersList
join roleUserLinks in userLinksList
on users.UserID equals roleUserLinks.UserID into roleUserLinksJoin
// left join
from roleUserLinks in roleUserLinksJoin.DefaultIfEmpty()
where
// has never been added to a role ie record isn't there
roleUserLinks == null
// has been soft deleted from a role so we want this record
|| roleUserLinks.State == "del"
// has been added to role so we don't want this record
&& !roleUserLinksJoin.Where(x=> x.State == "add" && x.UserID == roleUserLinks.UserID).Any()
select users).Distinct();
var res = z.ToList();
}
public class User
{
public int UserID { get; set; }
}
public class RoleUserLink
{
public int UserID { get; set; }
public string State { get; set; }
}
它返回 id 为 1 和 3 的用户。正如我所料。UserId:1
仅与 status 有联系delete
。UserId:3
没有任何链接。并且UserId:2
不会返回,因为它也与 status 链接add
。