解析linq表达式 [英] Parsing a linq expression
问题描述
说我们有以下内容:
Say we have the following:
public List<T> Query<T>(Predicate<T> where)
{
// do query here
return list;
}
我们这样称呼上面的内容:
And we are calling the above like this :
var return = Query<SaleInvoiceRow>(row => row.SerialNumber>200 && row.Code < 1000);
如何获取表达式详细信息,以便查询自定义数据源?
How can we get the expression details so we can query our custom data source?
for example -> [FieldName : SerialNumber, Operator : greaterthan, Value : 200 ] AND [ FieldName : Code, Operator: lessthan, Value : 1000 ]
推荐答案
:
How about:
static readonly List<int> data = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
static IEnumerable<int> SelectData(Predicate<int> selector)
{
return from d in data where selector(d) select d;
}
static void Main(string[] args)
{
Console.WriteLine("data = {0}", string.Join(",", SelectData(d => d>4)));
}
在此示例中,它是int类型,但可以是您喜欢的任何类型.在der谓词委托中,您可以访问SaleInvoiceRow实例的任何成员.
干杯
Andi
In this example, it is the int type, but it can be any type you like. In der Predicate delegate, you may access any member of the SaleInvoiceRow instance.
Cheers
Andi
第一个解决方案不是所要的.第二次尝试:;-)
请参阅 http://msdn.microsoft.com/en-us/library/bb397951.aspx [ ^ ]作为起点.
The 1st solution was not what was asked for. 2nd attempt: ;-)
See http://msdn.microsoft.com/en-us/library/bb397951.aspx[^] as starting point.
static readonly List<int> data = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
static IEnumerable<int> SelectData(Expression<Predicate<int>> selector)
{
ParameterExpression param = (ParameterExpression)selector.Parameters[0];
BinaryExpression operation = (BinaryExpression)selector.Body;
ParameterExpression left = (ParameterExpression)operation.Left;
ConstantExpression right = (ConstantExpression)operation.Right;
Console.WriteLine("Decomposed expression: {0} => {1} {2} {3}",
param.Name, left.Name, operation.NodeType, right.Value);
//...
return from d in data where selector.Compile()(d) select d;
}
static void Main(string[] args)
{
Console.WriteLine("data = {0}", string.Join(",", SelectData(d=>d>4)));
}
结果输出为:
The resulting output is:
Decomposed expression: d => d GreaterThan 4
data = 5,6,7,8,9
您必须使表达式的解析更加复杂.在上面的示例中,假设有一个二进制运算作为lambda表达式的主体.
干杯
安迪
You have to make the parsing of the expression far more sophisticated. In the example above, the assumption is that there is exactly one binary operation as body of the lambda expression.
Cheers
Andi
这篇关于解析linq表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!