Optimizing linq queries with .Any() instead of .Count()

By on in , with No Comments

If you have any linq code that looks like this:

var query = (from cust in Customer
             where cust.CustomerId == customerId 
             select cust);
return (query.Count() != 0);

Replace it with code that looks like this:

var query = (from cust in Customer
             where cust.CustomerId == customerId 
             select cust);
return (query.Any());

Basically you save time since linq doesn’t need to count each and every record in the collection.

« »