Dynamic LINQ

Updated: Dynamic LINQ in an Assembly Near By

Included with Microsoft's .NET samples, which you can get here lies an hidden gem: a set of method extensions for IQueryable and IQueryable<T> that allow execution of lambda expressions specified as strings, which is handy if you want to generate expressions dynamically.

The actual code is in the CSharpSamples\LinqSamples\DynamicQuery folder. I think Microsoft could have arranged it slightly better, in order to promote quicker reuse, but probably that wasn't on their minds. The extensions are offered by class DynamicQueryable and consist of:

  • GroupBy
  • OrderBy
  • Select
  • Skip
  • Take
  • Where

There are also other useful classes, like DynamicExpression, which parses a String into a lambda.

With these, you can do things like:


Func<SomeClass, Boolean> filterExpression = DynamicExpression.ParseLambda<SomeClass, Boolean>("SomeProperty == true && SomeOtherProperty > 10");  //create lambda from string
var list = dataSource.OrderBy("PropertyName").Take("10").Skip("1").ToList();  //string instead of lambda

For your convenience, I attach a DLL which only contains the reusable parts of the project, in the System.Linq.Dynamic namespace. I have been using this, and I find it very helpful, have a look at it, and happy dynamic LINQing!

Bookmark and Share

                             

9 Comments

Comments have been disabled for this content.