Linq条件DefaultIfEmpty查询过滤器

时间:2015-06-15 04:50:26

标签: c# linq asp.net-mvc-5 linq-query-syntax

我的查询如下:

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 Outer Join而不是Inner Join。

然而,由于我使用了烦人的物体,我无法弄清楚如何正确地做到这一点。所以我希望能够在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匿名对象

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

我通过在初始查询后添加过滤器来解决它,检查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);
}