Reputation: 1425
Hi I have the following code:
if (!_jobs.Any(j => j.Id == emailJob.Id))
{
}
This code should find any elements which satisfy the condition. So I would assume that it should return after finding the first element, something like this:
if (!_jobs.FirstOrDefault(j => j.Id == emailJob.Id) != null)
{
}
Resharper tries to simplify this LINQ expression to:
if (_jobs.All(j => j.Id != emailJob.Id))
{
}
This seems less efficient to me because it has to check that every single element satisifies the inverse condition.
Sorry if I'm just misunderstanding how LINQ works.
Joe
Upvotes: 2
Views: 582
Reputation: 1411
Both Any
and All
will stop looking immediately upon the condition failing.
If you are looking for more than just taking our word or anecdotal evidence, you can see from the source that this is what it is doing.
There is an extra inversion in the All
method after the predicate is applied. This is a relative 0 performance impact, so code readability is the main concern.
Upvotes: 3
Reputation: 86074
If there is any job that does match the emailJob id, then the .Any()
approach can abort early. By the same token, the .All()
approach can stop working as soon as it finds a condition that's false, which will happen at the same job. The efficiency should be about the same.
Upvotes: 1
Reputation: 437356
The two versions are mirror approaches and do exactly the same amount of work.
When you say "if none of the items satisfy this condition" (!Any
), then all of the items have to be checked in order to get a definite answer.
ReSharper's suggestion is useful because it guides you towards using the method that more clearly shows what is going to happen: All
jobs will have to be examined.
Upvotes: 7