如何在System.Linq.Dynamic ExpressionParser中实现SelectMany [英] How to implement SelectMany in System.Linq.Dynamic ExpressionParser
问题描述
我正在尝试在动态linq表达式解析器中实现SelectMany语句,这样我就可以像这样运行查询:
I'm trying to implement the SelectMany statement inside of the dynamic linq expresion parser, such that I could run a query like so:
Customers.Select("Orders.SelectMany(OrderItems)")
与linq查询等同:
Customers.Select(cust => cust.Orders.SelectMany(ord => ord.OrderItems))
我尝试将SelectMany添加到System.Linq.Dynamic.ExpressionParser的IEnumerableSignatures中,但看来还有很多事情要做.
I've tried adding SelectMany to the IEnumerableSignatures of System.Linq.Dynamic.ExpressionParser, but it looks like there's more I need to do.
我已经研究了这个Codeplex项目,但是却一无所获: http://dynamiclinq.codeplex. com/具体来说,它不会运行我的旧查询,并且不支持select或select many.
I've looked into this codeplex project but didn't get anywhere with it: http://dynamiclinq.codeplex.com/ specificaly it wouldn't run my old queries and didn't have support for select or select many.
最终我想在动态linq语句中使用所有无数的linq语句.
Ultimately I'd like to use all of the ienumerable linq statements inside of a dynamic linq statement.
推荐答案
要使SelectMany在动态linq查询中工作,您不仅应修改IEnumerableSignatures,而且还应更改ParseAggregate方法,以便为SelectMany传递特定的typeArgs: >
For make SelectMany work inside dynamic linq queries you shoud not only modify IEnumerableSignatures, but also change ParseAggregate method to pass specific typeArgs for SelectMany, in this way:
Expression ParseAggregate(Expression instance, Type elementType, string methodName, int errorPos)
{
...
Type[] typeArgs;
if (signature.Name == "Min" || signature.Name == "Max")
{
typeArgs = new Type[] { elementType, args[0].Type };
}
else if(signature.Name == "Select")
{
typeArgs = new Type[] { elementType, Expression.Lambda(args[0], innerIt).Body.Type };
}
else if(signature.Name == "SelectMany")
{
var type = Expression.Lambda(args[0], innerIt).Body.Type;
var interfaces = type.GetInterfaces().Union(new[] { type });
Type resultType = interfaces.Single(a => a.Name == typeof(IEnumerable<>).Name).GetGenericArguments()[0];
typeArgs = new Type[] { elementType, resultType };
}
else
{
typeArgs = new Type[] { elementType };
}
...
}
这篇关于如何在System.Linq.Dynamic ExpressionParser中实现SelectMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!