Linq 条件默认值如果为空查询筛选器

本文关键字:查询 筛选 条件 默认值 如果 Linq | 更新日期: 2023-09-27 17:56:06

>我有一个查询如下:

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,从而使它成为左外部连接而不是内部连接。

但是,由于我正在使用烦人的对象,因此我不知道如何正确执行此操作。因此,我希望能够在左联接和内联接之间切换,而无需复制整个查询,例如:

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 匿名对象。

Linq 条件默认值如果为空查询筛选器

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

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