gpt4 book ai didi

c# - 使用 Linq.Expressions.Expression 排序

转载 作者:行者123 更新时间:2023-11-30 19:11:15 24 4
gpt4 key购买 nike

我写了这段代码来对 IQueryable<T> 进行排序按专栏sortColumn .我想扩展它,以便具有列值的条目 BirthDate等于DateTime.Today将在排序中排在第一位,但我找不到或想不出如何完成这项工作。

public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string sortColumn, bool asc)
{
var param = Expression.Parameter(typeof(T), "p");

var prop = Expression.Property(param, sortColumn);

var exp = Expression.Lambda(prop, param);

string method = asc ? "OrderBy" : "OrderByDescending";

Type[] types = new[] { q.ElementType, exp.Body.Type };

var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);

return q.Provider.CreateQuery<T>(mce);
}

最佳答案

参见 Handle GridView.OnSorting() and create sorting expression dynamically using LINQ

public static class SortExpressionBuilder<T>
{
private static IDictionary<SortDirection, ISortExpression> directions = new Dictionary<SortDirection, ISortExpression>
{
{ SortDirection.Ascending, new OrderByAscendingSortExpression() },
{ SortDirection.Descending, new OrderByDescendingSortExpression() }
};

interface ISortExpression
{
Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> GetExpression();
}

class OrderByAscendingSortExpression : ISortExpression
{
public Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> GetExpression()
{
return (c, f) => c.OrderBy(f);
}
}

class OrderByDescendingSortExpression : ISortExpression
{
public Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> GetExpression()
{
return (c, f) => c.OrderByDescending(f);
}
}

public static Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> CreateExpression(SortDirection direction)
{
return directions[direction].GetExpression();
}
}

public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> collection, string columnName, SortDirection direction)
{
ParameterExpression param = Expression.Parameter(typeof(T), "x"); // x
Expression property = Expression.Property(param, columnName); // x.ColumnName
Func<T, object> func = Expression.Lambda<Func<T, object>>( // x => x.ColumnName
Expression.Convert(Expression.Property(param, columnName),
typeof(object)), param
).Compile();

Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> expression = SortExpressionBuilder<T>.CreateExpression(direction);
IEnumerable<T> sorted = expression(collection, func);
return sorted;
}

以及底部的链接:

关于c# - 使用 Linq.Expressions.Expression 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12284085/

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