嵌套的SelectMany /选择LINQ DynamicQueryable

时间:2014-07-02 04:07:48

标签: c# linq dynamicquery

如何将此LINQ查询转换为动态查询?

var resultList = itemList.SelectMany(b => b.SubItemList.Select(x => new {b.Supplier,
b.Customer, x.ProductCode, x.ProductPrice}));

我有这个方法:

public static IQueryable SelectMany(this IQueryable source, string selector, params     object[] values)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (selector == null)
            throw new ArgumentNullException("selector");

        // Parse the lambda
        LambdaExpression lambda =
            DynamicExpression.ParseLambda(source.ElementType, null, selector, values);

        // Fix lambda by recreating to be of correct Func<> type in case 
        // the expression parsed to something other than IEnumerable<T>.
        // For instance, a expression evaluating to List<T> would result 
        // in a lambda of type Func<T, List<T>> when we need one of type
        // an Func<T, IEnumerable<T> in order to call SelectMany().
        Type inputType = source.Expression.Type.GetGenericArguments()[0];
        Type resultType = lambda.Body.Type.GetGenericArguments()[0];
        Type enumerableType = typeof(IEnumerable<>).MakeGenericType(resultType);
        Type delegateType = typeof(Func<,>).MakeGenericType(inputType, enumerableType);
        lambda = Expression.Lambda(delegateType, lambda.Body, lambda.Parameters);

        // Create the new query
        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "SelectMany",
                new Type[] { source.ElementType, resultType },
                source.Expression, Expression.Quote(lambda)));
    }

我可以像

一样使用它
var resultList = itemList.SelectMany("SubItemList");

但是我的SelectMany内部选择怎么样?如何创建嵌套动态查询? 谢谢!

0 个答案:

没有答案