gpt4 book ai didi

c# - 如何将 Microsoft 的 Dynamic Linq 的 OrderBy 存储在变量中?

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:08 24 4
gpt4 key购买 nike

这里是 Generic Repository存储 OrderBy 的方式:

private Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy;

这是 Microsoft 的 OrderBy,它接受一串字段名称(来自 Microsoft's Dynamic Linq ):

public static IQueryable<T> OrderBy<T>(
this IQueryable<T> source,
string ordering, params object[] values);

这是我们的扩展方法,它将我们的字段数组转换为逗号分隔的 OrderBy/ThenBy:

public static IQueryable<T> OrderBy<T>(
this IQueryable<T> source,
ICollection<string> orderBy)
{
return source.OrderBy( String.Join(",", orderBy) );
}

一切正常,但需要将 OrderBy 附加到原始实体。 我们如何将 OrderBy 保存在变量中以便稍后附加到该实体?

//Something like 
Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy = ??

作为引用,这里是 Microsoft 的 System.Linq.Dynamic.DynamicQueryable.OrderBy 来源 ( Scott G's writeup link ):

public static IQueryable<T> OrderBy<T>(
this IQueryable<T> source, string ordering, params object[] values)
{
return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values);
}

public static IQueryable OrderBy(
this IQueryable source, string ordering, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (ordering == null) throw new ArgumentNullException("ordering");
ParameterExpression[] parameters = new ParameterExpression[]
{
Expression.Parameter(source.ElementType, "")
};
ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
Expression queryExpr = source.Expression;
string methodAsc = "OrderBy";
string methodDesc = "OrderByDescending";
foreach (DynamicOrdering o in orderings)
{
queryExpr = Expression.Call(
typeof(Queryable),
o.Ascending ? methodAsc : methodDesc,
new Type[] { source.ElementType, o.Selector.Type },
queryExpr,
Expression.Quote(Expression.Lambda(o.Selector, parameters)));
methodAsc = "ThenBy";
methodDesc = "ThenByDescending";
}
return source.Provider.CreateQuery(queryExpr);
}

最佳答案

这是你要找的吗?

Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy = t => t.OrderBy( String.Join(",", orderBy));

关于c# - 如何将 Microsoft 的 Dynamic Linq 的 OrderBy 存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29034975/

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