Linq Conditional DefaultIfEmpty query filter

1.5k views Asked by At

I have a query as below:

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

This works correctly. However, I have a boolean variable that should determine whether the join to e.PractitionerProfiles should have DefaultIfEmpty, thereby making it a Left Outer Join instead of an Inner Join.

However, as I am using annoymous objects, I can't figure out how to do it correctly. So I want the ability to switch between Left and Inner Join without duplicating the whole query like:

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

Is there a clean way to do it with one query? The problem also is that I have a number of further conditions which get placed on it, so declaring query inside the loop means it doesn't have a local variable and I don't know how to create an empty IQueryable anonymous object.

2

There are 2 answers

0
Rhys Stephens On BEST ANSWER

I solved it by adding the filter after the initial query, checking if the e.PractitionerProfiles were null.

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

then

if (variable)
{
    query = query.Where(x => x.profile != null);
}
2
Andrei Tătar On

Why not use ternary operator?

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