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(); 
  • 相关阅读:
    初学java之触发响应事件举例子
    初学java之(盒子分布)
    java(课程设计之记事本界面部分代码公布)
    HDUOJ---1236 排名(浙大考研题)
    HDUOJ----1234 开门人和关门人(浙江大学考研题)
    HDUOJ----2571(命运)(简单动态规划)
    初学java之面板布局的控制
    初学java之常用组件
    初学java之触发响应事件
    课程设计(部分代码)之java版(记事本)
  • 原文地址:https://www.cnblogs.com/hun_dan/p/2735255.html
Copyright © 2011-2022 走看看