How do I build up LINQ dynamically

21,270

Solution 1

If you are talking about a string Where clause (rather than building the expression etc yourself) - then the Dynamic LINQ Library (in the 3.5 samples, IIRC) should suffice.

Note that the example below is for database usage; but you can use it with LINQ-to-Objects by calling .AsQueryable() on your in-memory data.

alt text

Solution 2

Actually, there is a specific library from Microsoft (System.Linq.Dynamic) that comes with the C# VS2008 samples that supports this. Get it from here (Microsoft Download)

The library is included in the \LinqSamples\DynamicQuery directory of the samples of above download.

For extensive usage examples check this page: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Solution 3

Also you can use expression trees to created dynamic queries. See:

http://msdn.microsoft.com/en-us/library/bb397951.aspx

http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees

http://blogs.msdn.com/charlie/archive/2008/01/31/expression-tree-basics.aspx

Share:
21,270
Jabezz
Author by

Jabezz

Just another developer

Updated on July 19, 2022

Comments

  • Jabezz
    Jabezz almost 2 years

    I have a scenario where I have custom configured column names, associated operators like < > = between etc. and then a value associated.

    I'm trying to determine if it is possible to build up a LINQ query with a dynamic (string) where clause?

    I've noticed the Predicate.OR Preditcate.AND stuff, but that is not quite what I'm talking about.

    Any suggestions?