Using .Any to optimize linq queries.
If you have linq code that uses the .Count() function to check to see if an item exists then you can use .Any() to do the same thing, just faster.
replace code like this:
var query = (from cust in Customer
where cust.CustomerId == customerId
select cust);
return (query.Count() == 0);
with this:
var query = (from cust in Customer
where cust.CustomerId == customerId
select cust); return (query.Any());
Written by Michael Griffith
Related protips
2 Responses
What´s the background of this benefit? Why does this work?
over 1 year ago
·
The Count function will wait until it's counted everything in the list. The Any function returns true on the first item it finds in the list, so you don't have to wait until everything in the list has been counted.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#