Dynamic LINQ and Dynamic Lambda expressions?
Solution 1
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.
Solution 2
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.
Solution 3
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.
Sklivvz
Stack Overflow Contributor since 2008 Skeptics mod since 2011 Core dev since March 2013 Stack Overflow alumnus since February 2017 You can find me on Personal site Twitter @sklivvz Github
Updated on July 09, 2022Comments
-
Sklivvz almost 2 years
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.
-
aku over 15 yearsI don't know "best-practices" for such things. I know how to solve concrete problem, but general "best way" is too vague matter.
-
David Robbins about 14 yearsSound advice. We did that for configuration of workflows and it works quite nicely.
-
D_Bye over 12 yearsthe only downside is that you may run into issues with full/partial trust that would prevent your code from executing in asp.net