zoukankan      html  css  js  c++  java
  • Entity Framework 多字段排序

    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(); 
  • 相关阅读:
    OC-KVO简介
    注册审核
    应用权限
    关于函数执行的一点知识
    设置权限
    文件操作实例:文件管理器(网页版)
    文件操作
    正则表达式
    全局变量和递归
    案例:简单留言板
  • 原文地址:https://www.cnblogs.com/hun_dan/p/2735255.html
Copyright © 2011-2022 走看看