Question

What is the best way of dynamically writing LINQ queries and Lambda expressions?

I am thinking of applications where the end user can design business logic rules, which then must be executed.

I am sorry if this is a newbie question, but it would be great to get best practices out of experience.

Was it helpful?

Solution

I cannot recommend higher than you reading through the postings of Bart De Smet (http://community.bartdesmet.net/blogs/bart/), he is really brilliant when it comes to Lambda.

His recent series covered dynamic Lambda, starting with http://community.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-0.aspx

Absolutely beautiful code.

OTHER TIPS

Another possibility is to integrate a scripting runtime into your program, so that your users can write the business logic in a DSL. IronPython would be a candidate.

I can see two ways you can dynamically generate lambda's. You could try Reflection.Emit to generate IL (the .Net bytecode) directly and call them as a lambda or you can use the System.CodeDom and Microsoft.CSharp.CSharpCodeProvider to generate the code from higher level constructs. What you want to do depends on how you want the user to input this stuff. If you want the user to write C# then you can just use the built in compliler.

Generating Linq dynamically should be easier. You should be able to generate LINQ queries as expression trees in runtime and then pass them into an IQueryable to execute. I'd suggest you look into the documentation on IQueryable to learn more about this. Another way would be to pre-define a couple of linq queries and then allow the user to chain them together. This should be workable because any Linq query returns an IEnumerable that can be consumed by the next Linq query.

Lambda expressions can be easily created via the System.Linq.Expressions namespace.

System.Linq.Expressions is what you need. I've written a nice UI that lets users define and build queries dynamically in the form of an expression tree. You can then hand this off to Linq2SQL or client of your choice.

I don't understand what do you mean saying "best way". It would be better to provide simple example of what you want to achieve. Composing dynamic LINQ expression is not hard but tricky.

Here is an example of dynamic linq expression creation:

How do I compose existing Linq Expressions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top