-k-zsg
Last Updated: February 25, 2016
·
798
· 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());
Say Thanks
Respond

2 Responses
Add your response

8437
10154941 475885639207813 910458244034183173 n

What´s the background of this benefit? Why does this work?

over 1 year ago ·
8448

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 ·