8

I am working with Entity Framework 4.1 and C#.

Which one is the most suitable for best performance?

If so - why? (any links for additional readings) ?

bool isBoarding = invoice.Allocations.Where(a => a.Service.Key == "boarding").Count() > 0;

OR

bool isBoarding = invoice.Allocations.Any(a => a.Service.Key == "boarding");
1
  • Any is more readable and is normally more efficient since it can use EXISTS. But in Linq-To-Entities you should look at the generated sql. Sometimes Count seems to be faster. For Linq-To-Objects always use Any. Nov 22, 2012 at 11:19

1 Answer 1

10

Count I believe will cause all records to be iterated over, whereas Any will stop at the first it finds.

EDIT: Just found an excellent post about count vs any take a look here

2
  • 2
    The post that you link is about Ienumerable but in responses it talk about Iqueriable and EF Jan 17, 2014 at 17:34
  • Indeed, In general when using linq to objects Any is almost always faster, however when using Linq to entities Count() > 0 can be faster, purely it seems because of the often convoluted SQL generated by EF.
    – BLoB
    Jan 18, 2014 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.