Linq 条件 DefaultIfEmpty 查询过滤器

Linq Conditional DefaultIfEmpty query filter

我有如下查询:

bool variable = false//or true


var query = from e in _repository.GetAll<Entity>()
            from u in e.Users
            where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId
            from p in e.PractitionerProfiles.DefaultIfEmpty()
            select new { entity = e, user = u, profile = p };

这工作正常。但是,我有一个布尔变量,它应该确定 e.PractitionerProfiles 的连接是否应该有 DefaultIfEmpty,从而使它成为左外部连接而不是内部连接。

但是,由于我使用的是烦人的对象,所以我不知道如何正确地使用它。所以我希望能够在不复制整个查询的情况下在 Left 和 Inner Join 之间切换,例如:

if(variable) {
            var query = from e in _repository.GetAll<Entity>()
                        from u in e.Users
                        where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId
                        from p in e.PractitionerProfiles
                        select new { entity = e, user = u, profile = p };
}
else {
            var query = from e in _repository.GetAll<Entity>()
                        from u in e.Users
                        where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId
                        from p in e.PractitionerProfiles.DefaultIfEmpty()
                        select new { entity = e, user = u, profile = p };
}

有没有一种简单的方法可以通过一个查询来完成?问题还在于我有一些进一步的条件,所以在循环内声明查询意味着它没有局部变量,我不知道如何创建一个空的 IQueryable 匿名对象。

为什么不使用三元运算符?

from p in (variable ? e.PractitionerProfiles : e.PractitionerProfiles.DefaultIfEmpty())

我通过在初始查询后添加过滤器解决了这个问题,检查 e.PractitionerProfiles 是否为空。

    var query = from e in _repository.GetAll<Entity>()
                from u in e.Users
                where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId
                from p in e.PractitionerProfiles.DefaultIfEmpty()
                select new { entity = e, user = u, profile = p };

然后

if (variable)
{
    query = query.Where(x => x.profile != null);
}