7

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");
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Sampath
  • 58,546
  • 53
  • 279
  • 406
  • `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](http://stackoverflow.com/a/11042691/284240) `Count` seems to be faster. For Linq-To-Objects [always](http://stackoverflow.com/a/305156/284240) use `Any`. – Tim Schmelter Nov 22 '12 at 11:19
  • Thanks for the useful links. – Sampath Nov 22 '12 at 15:03

1 Answers1

9

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

Community
  • 1
  • 1
Paul Zahra
  • 9,183
  • 7
  • 51
  • 72
  • 1
    The post that you link is about Ienumerable but in responses it talk about Iqueriable and EF – Marco Staffoli Jan 17 '14 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. – Paul Zahra Jan 18 '14 at 09:26