Sklivvz
Sklivvz

Reputation: 31133

Dynamic LINQ and Dynamic Lambda expressions?

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.

Upvotes: 14

Views: 26847

Answers (6)

flesh
flesh

Reputation: 23935

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.

Upvotes: 0

Aaron Powell
Aaron Powell

Reputation: 25099

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.

Upvotes: 11

TraumaPony
TraumaPony

Reputation: 10794

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

Upvotes: 0

aku
aku

Reputation: 123974

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

Upvotes: -1

Torsten Marek
Torsten Marek

Reputation: 86502

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.

Upvotes: 2

Mendelt
Mendelt

Reputation: 37483

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.

Upvotes: 1

Related Questions