1. Any or Count?
When you have to test for the presence of at least one element into a list, use
if (query.Any())
Instead of
if (query.Count() > 0)
That way it only needs to find the first match.
2. Conditions
Use
query.FirstOrDefault(x => x.value > 1);
query.SingleOrDefault(x => x.value > 1);
Instead of
query.Where(x => x.value > 1).FirstOrDefault();
query.Where(x => x.value > 1).SingleOrDefault();
That way it only does one operation instead of two concatenated operations
3. Understand how it works
You always need to struggle for performance as a LINQ Developer; perhaps because to understand better how internal mechanism works.
using (MYDataContext context = new MYDataContext())
{
var customers = from cust in context.Customers
select cust;
foreach (var customer in customer)
Response.Write(customer.CustomerAddresses.Count().ToString());
}
In above example, you will see in Sql Server Profiler that for each customer one query will be executed additional each times to get the total addresses count for that customer when you enumerates in foreach loop. Now, consider below re-written snippet:
using (MYDataContext context = new MYDataContext())
{
var customers = from cust in context.Customers
select cust;
DataLoadOptions dataLoadOptions = new DataLoadOptions();
dataLoadOptions.LoadWith(A => A.CustomerAddresses);
context.LoadOptions = dataLoadOptions;
foreach (var customer in customer)
Response.Write(customer.CustomerAddresses.Count().ToString());
}
Simply in above example, with DataLoadingOptions we are infect just telling LINQ Query engine that while it fetches the Customer data; also fetch associated CustomerAddresses table record count for that particular Customer. The benefit is; only ONE query will be executed to get the final result.
4. Finally
The success behind a LINQ application that you develop lies behind the performance of the query that you formulate. You can use any third party tool like I prefer to use LINQPad (by Joseph Albahari) while my development with LINQ. Actually, quick since a long time after I got to know about this tool and I was impressed so much that I thought to why not I get aware something about such nice and intelligent tool before. Life would have become easier!