gpt4 book ai didi

dynamicquery - 以 System.Linq.Dynamic 的方式动态调用 SelectMany

转载 作者:行者123 更新时间:2023-12-01 09:38:52 25 4
gpt4 key购买 nike

在 System.Linq.Dynamic 中,有几种方法可以动态形成 Select、Where 和其他 Linq 语句。但是 SelectMany 没有。

Select的方法如下:

    public static IQueryable Select(this IQueryable source, string selector, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values);
IQueryable result = source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Select",
new Type[] { source.ElementType, lambda.Body.Type },
source.Expression, Expression.Quote(lambda)));

return result;
}

我试图修改上面的代码,经过几个小时的工作,我找不到出路。

欢迎提出任何建议。

最佳答案

已经为我们的项目实现了这个,让我知道它是否适合你!

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)));
}

关于dynamicquery - 以 System.Linq.Dynamic 的方式动态调用 SelectMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com