var query = from c in context.Customers select c; if (name != null) query = query.Where ( customer => customer.Name == name ); if (contactName != null) query = query.Where ( customer => customer.ContactName == contactName );
This way we can pass different combinations of arguments to the method and it will still build the correct where clause that executes at database level.
Do note that this only works when the different criteria should be “AND”‘ed together, but it’s still pretty useful for use cases like the one above.
Some advanced techniques are described here :
Implementing Dynamic Searching Using LINQ @ MSDN