I'd like to allow my users to write and execute linq queries. For this, I need a linq parser. This parser would understan开发者_如何学Cd only linq expression, not the full C# language.
So, for example, if we have class Order { public int OrderId; } List list = ...
the user should be able to enter in the UI "select p in list where p.OrderId > 2"; And this would return the orders where orderId > 2.
Does it exist?
The quickest way to do it is to:
Embed the expression into an C# file that will generate a method that will return the query as Expression>; e.g., for
from x in Foos select x.Y
You might emit:
class Wrapper { IEnumerable<blah> Foos; public static Expression<Func<object>> Expr { get { return from x in Foos select x.Y; } } }
Invoke the C# compiler on the file.
- Load the resulting assembly.
- Access the property
- Use the Linq tree to your heart's content.
As a byproduct you get type checking and a bunch of other things. The only real downside is you need a good understanding of the environment in which the query will be executing; if one of the things you're trying to do is to understand the environment, then this doesn't help you very much.
You can create your own Linq providers, here's a walk through on MSDN
精彩评论