Use All or Negation of Any

74 Views Asked by At

Using Entity Framework Core 2.2 I have the following queries:

dbContext.Projects.Where(x => x.Jobs.All(y => y.UserId != userId)) 

dbContext.Projects.Where(x => !x.Jobs.Any(y => y.UserId == userId))

So I am getting all projects which does not have any Job where Job.UserId equals userId.

I believe both do the same but which one is fastest?

1

There are 1 best solutions below

0
On BEST ANSWER

These are fully equivalent, thus should have one and the same performance in any normal query provider implementation.

Speaking about EF Core, both are translated to one and the same SQL using NOT EXISTS (subquery) criteria, so the performance of executing the SQL query is one and the same. Of course since SQL has not special construct for All (SQL EXISTS == LINQ Any), the translation of All should be slightly slower than translation of Any (basically has to convert it to the negated version of Any), but negligible compared with the time of executing and materializing the query.

So in general use the one which gives you better readability. I personally prefer Any because it naturally maps to SQL, thus has bigger chance to be supported by the query provider. But since EF Core supports both, it's really a matter of taste.