Entity Frameworkマルチフィールドソート

5360 ワード

public interface IOrderByExpression<TEntity> where TEntity : class

{

    IOrderedQueryable<TEntity> ApplyOrderBy(IQueryable<TEntity> query);

    IOrderedQueryable<TEntity> ApplyThenBy(IOrderedQueryable<TEntity> query);

}

 
public class OrderByExpression<TEntity, TOrderBy> : IOrderByExpression<TEntity>

    where TEntity : class

{

    private Expression<Func<TEntity, TOrderBy>> _expression;

    private bool _descending;



    public OrderByExpression(Expression<Func<TEntity, TOrderBy>> expression,

        bool descending = false)

    {

        _expression = expression;

        _descending = descending;

    }



    public IOrderedQueryable<TEntity> ApplyOrderBy(

        IQueryable<TEntity> query)

    {

        if (_descending)

            return query.OrderByDescending(_expression);

        else

            return query.OrderBy(_expression);

    }



    public IOrderedQueryable<TEntity> ApplyThenBy(

        IOrderedQueryable<TEntity> query)

    {

        if (_descending)

            return query.ThenByDescending(_expression);

        else

            return query.ThenBy(_expression);

    }

}

 
public IQueryable<TEntity> ApplyOrderBy<TEntity>(IQueryable<TEntity> query,

    params IOrderByExpression<TEntity>[] orderByExpressions)

    where TEntity : class

{

    if (orderByExpressions == null)

        return query;



    IOrderedQueryable<TEntity> output = null;



    foreach (var orderByExpression in orderByExpressions)

    {

        if (output == null)

            output = orderByExpression.ApplyOrderBy(query);

        else

            output = orderByExpression.ApplyThenBy(output);

    }



    return output ?? query;

}
var query = context.Users ... ;



var queryWithOrderBy = ApplyOrderBy(query,

    new OrderByExpression<User, string>(u => u.UserName),    // a string, asc

    new OrderByExpression<User, int>(u => u.UserId, true));  // an int, desc



var result = queryWithOrderBy.ToList();