Store multi-type OrderBy expression as a property

前端 未结 4 2068
一向
一向 2020-12-15 12:57

In a generic abstract base class I\'m storing a couple of expressions used for ordering:

public Expression> OrderByString { get;          


        
4条回答
  •  臣服心动
    2020-12-15 13:01

    Amy B's answer is great, and I based my own solution on it. So my point is more of an improvement for what I needed, which I am likely to improve upon in time.

    public interface IOrderer
    {
        IOrderedQueryable Apply(IQueryable source);
    }
    
    public class OrderBy : IOrderer
    {
        private Expression> _orderExpr;
        public OrderBy(Expression> orderExpr)
        {
            _orderExpr = orderExpr;
        }
    
        public IOrderedQueryable Apply(IQueryable source)
        {
            return source.OrderBy(_orderExpr);
        }
    }   
    
    public class ThenBy : IOrderer
    {
        private Expression> _orderExpr;
        public ThenBy(Expression> orderExpr)
        {
            _orderExpr = orderExpr;
        }
    
        public IOrderedQueryable Apply(IQueryable source)
        {
            return ((IOrderedQueryable)source).ThenBy(_orderExpr);
        }
    }   
    
    public class OrderCoordinator
    {
        public List> Orders { get; private set; } = new List>();
    
        public IQueryable ApplyOrder(IQueryable source)
        {
            foreach (IOrderer orderer in Orders)
            {
                source = orderer.Apply(source);
            }
            return source;
        }
    
        public OrderCoordinator OrderBy(Expression> orderByExpression)
        {
            Orders.Add(new OrderBy(orderByExpression));
            return this;
        }
    
        // Can add more sort calls over time
        public OrderCoordinator ThenBy(Expression> orderByExpression)
        {
            Orders.Add(new ThenBy(orderByExpression));
            return this;
        }
    }   
    

    Specify Coordinator with type:

    public OrderCoordinator OrderCoordinator { get; private set; } = new OrderCoordinator();
    

    Specify sort ordering:

    OrderCoordinator.OrderBy(e => e.MyStringProperty).ThenBy(e => e.MyIntProperty);
    

    Apply the ordering:

    ordered = OrderCoordinator.ApplyOrder(ordered); 
    

提交回复
热议问题