Last Updated: February 25, 2016
·
1.569K
· mwgriffith

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());

2 Responses
Add your response

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 ·