排序使用Linq.Expressions.[removed]Sort using Linq.Expr

2019-09-22 03:57发布

我写了这个代码进行排序的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);
}

Answer 1:

看到手柄GridView.OnSorting(),并创建排序表达动态使用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;
}

从底部的链接:

  • 排序使用lambda / LINQ到对象列表
  • GridView的排序:SortDirection总是升序


Answer 2:

您可以尝试进行排序类似于下面的表达式的东西:

.OrderBy(x => BirthDate == DateTime.Now.Date ? 0 : 1).ThenBy(sortColumn);


文章来源: Sort using Linq.Expressions.Expression