A vew things I often do:
1) Layout: always start a query at the next line. Example:
Don't do this
var allCustomersThatDontContainUnpayedOrders = from customer in db.Customers
where customer.Orders ...
select customer;
But do this:
var allCustomersThatDontContainUnpayedOrders =
from customer in db.Customers
where customer.Orders ...
select customer;
2) Use multiple where
clauses where you can. I try to find the second snippet more readable than the first:
var results =
from customer in db.Customers
where customer.Name.Contains(search) && customer.Address.City != null &&
customer.Employee.IsSenior
select customer;
var results =
from customer in db.Customers
where customer.Name.Contains(search)
where customer.Address.City != null
where customer.Employee.IsSenior
select customer;
3) Prevent joins if you can. LINQ to SQL often allows you to just 'dot' over all parent-child relations without using hard-to-understand join
statements.
4) Often you will see that many queries look alike. You might always want to filter certain records based on rights of a user. You can extract this code in a method:
var customers = db.Customers;
customers = FilterBasedOnUserRights(customers, currentUser);
public static IQueryable<Customer> FilterBasedOnUserRights(
IQueryable<Customers customers, User currentUser)
{
return
from customer in customers
where [big complicated where clause]
select customer;
}