In many LINQ (to SQL) related posts questions regarding the dynamic construction of LINQ queries arise. Most of the available answers deal with using LINQ's Expression classes to construct an expression tree at runtime. While this definitely is an elegant way, it's also extremely difficult for most object oriented programmers to understand. I'd therefore provide a little bit of an easier solution which simply constructs the where constraint from a string.
I admit that this takes away some of LINQ's type safeness and beauty and goes closely to creating an SQL command on the fly, however, it's inspired by a post from Anders Hejlsberg, the inventor of LINQ, so I assume it's not too wrong. ;-)
Here's the problem:
Suppose you've got a list of search terms which might vary at runtime and you want to declare a LINQ to SQL query which returns all Customers from the Nortwhind database, where the ContactName contains any of the search terms.
Here is the LINQ to SQL query that does exactly that:
code
string[] searchTerms = new string[] { "Maria", "Pedro" };
string search = "";
foreach (string searchTerm in searchTerms)
{
search += "ContactName.Contains(\""+searchTerm+"\") or ";
}
search += "1=0";
var query = db.Customers.Where(search).Select(c => c);
It's very straight forward: In the foreach loop we are concatenating a string which will serve as the condition for the where clause. In the above example this will evaluate to:
ContactName.Contains(\"Maria\") or ContactName.Contains(\"Pedro\") or 1=0
The "1=0" is only there because otherwise search would end with an "or" operator once the loop finishes and LINQ would not be able to parse it.
Before you copy and try to compile: Obviously the shipping version of LINQ to SQL does not support any overload for the Where extension method, that takes a single string parameter as its argument. In order to make the above compile you have to download and include further extension methods for LINQ from Microsoft. Once you've downloaded expand the archive and include the System.Linq.Dynamic namespace contained within the Dynamic.cs file LinqSamples\DynamicQuery\DynamicQuery.
I wondered why these methods did not make it into the final shipping build of LINQ but am happy that I finally found them!
Hope this helps!