Jonas Stawski

Everything .NET and More

Dynamic Construction of a LINQ Expression

One of the great things about LINQ is it's deferred execution. Read about deferred execution here and here. What does this mean to us developers? Well it means many things, but one of those things is that you can dynamically construct your LINQ expressions based on some input. Let's say you have a search form and you want to add the filters only when they are selected. You can easily do this like this:

var q = DB.Products.Where(p => p.Published);
 
if (categoryID != null)
    q = q.Where(p => p.CategoryID == categoryID);
 
if (!String.IsNullOrEmpty(description))
    q = q.Where(p => p.Description == description);
 
return q.ToList();
 

the code above is using extension methods. The code below is the same, but with T-SQL like syntax.

var q = from p in DB.Products
        where p.Published
        select p;
 
if (categoryID != null)
{
    q = from p in q
        where p.CategoryID = categoryID
        select p;
}
 
if (!String.IsNullOrEmpty(description))
{
    q = from p in q
        where p.Description = description
        select p;
}
 
return q.ToList();

 

Notice that on this example on the first query I'm selecting from DB.Products where everywhere else after that I select from q.

Happy Programming!

Add comment

biuquote
Loading