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");
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sampath
  • 63,341
  • 64
  • 307
  • 441
  • `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

1 Answers1

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

Community
  • 1
  • 1
Paul Zahra
  • 9,522
  • 8
  • 54
  • 76
  • 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