DarthVader
DarthVader

Reputation: 55022

Linq where clause with if condition

I have the following model:

class Project{
   bool IsDeleted {set;get;}
   ICollection<Document> Documents {set;get;}
}

class Document{
   Project Project {set;get;}
   int? ProjectId {set;get;}
}

I am querying Document repository, I want to get all the documents and also the documents whose project is not deleted.

        var documents = _repository.Include(p=>p.Project)
                                    .Where(m => m.IsDeleted == false)
                                    .Where(x=> x.Project.IsDeleted == false) 

However , this is not working, because some documents are associated with projects where some arent. Ie: The documents that project is null, should return but this case dont.

What s the correct way to do this?

Upvotes: 0

Views: 571

Answers (2)

user57508
user57508

Reputation:

.Where(arg => !arg.IsDeleted && (arg.Project == null || !arg.Project.IsDeleted))

With C# 6 the "Safe navigation operator" (?.) will get introduced, which brings following shortcut (similar to ??):

.Where(arg => !arg.IsDeleted && !(arg.Project?.IsDeleted ?? false))

Anyway: I am not sure if this will work with every Linq-provider (like EF) as you've tagged your question with generally.

Upvotes: 3

Matt Burland
Matt Burland

Reputation: 45135

Something like this:

.Where(m => !m.IsDeleted && (m.Project == null || !m.Project.IsDeleted))

You need to check if Project is null before checking if Project.IsDeleted. If you don't want the ones where project isn't null, then you just need:

.Where(m => !m.IsDeleted && m.Project != null && !m.Project.IsDeleted)

Remember: Shortcut evaluation is your friend. In the first example, if m.Project == null then the it will evaluate to true and it won't even attempt to check m.Project.IsDeleted and you won't get the NullReferenceException.

If you want ALL the orphaned (i.e. no project) documents AND the documents that have projects that aren't deleted (i.e. you only exclude documents that belong to deleted projects) then:

.Where(m.Project == null || !m.Project.IsDeleted)

Upvotes: 1

Related Questions