
September 16, 2009 14:55 by
Jon
When creating an advanced search you often need to dynamically create the Where statments in your SQL. Here is an easy way to do this in LINQ. In the example below orderID, lastName, firstName, shipped are all values retrieved from controls on the page.
var query = from orders in dataContext.MyOrdersTable
select orders;
if (orderID.HasValue)
{
query = query.Where(order => order.OrderID == orderID);
}
if (!string.IsNullOrEmpty(lastName))
{
query = query.Where(order => order.LastName == lastName);
}
if (!string.IsNullOrEmpty(firstName))
{
query = query.Where(order => order.FirstName == firstName);
}
if (shipped.HasValue)
{
query = query.Where(order => order.Shipped == shipped);
}
myGridView.DataSouce = query;
myGridView.DataBind();