Advertisement
Guest User

OrderBy

a guest
Sep 18th, 2017
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4.  
  5. namespace Core
  6. {
  7.     public enum OrderDirection
  8.     {
  9.         Ascending,
  10.         Descending
  11.     }
  12.  
  13.     public interface IOrderBy<TEntity>
  14.     {
  15.         OrderDirection Direction { get; set; }
  16.         LambdaExpression Selector { get; set; }
  17.     }
  18.  
  19.     public class OrderBy<TEntity> : IOrderBy<TEntity>
  20.     {
  21.         public OrderBy(string entity, OrderDirection direction = OrderDirection.Ascending)
  22.         {
  23.             if (string.IsNullOrWhiteSpace(entity))
  24.             {
  25.                 Selector = null;
  26.             }
  27.             else
  28.             {
  29.                 var parameter = Expression.Parameter(typeof(TEntity), "entity");
  30.                 var propertyOrField = entity.Split('.')
  31.                     .Aggregate<string, Expression>(parameter, Expression.PropertyOrField);
  32.                 var selector = Expression.Lambda(propertyOrField, parameter);
  33.  
  34.                 Selector = selector;
  35.             }
  36.  
  37.             Direction = direction;
  38.         }
  39.  
  40.         public OrderBy(Expression<Func<TEntity, dynamic>> func, OrderDirection direction = OrderDirection.Ascending)
  41.         {
  42.             if (func == null) throw new ArgumentNullException("func");
  43.             var unaryExpressionBody = func.Body as UnaryExpression;
  44.  
  45.             if (unaryExpressionBody == null)
  46.             {
  47.                 Selector = func;
  48.             }
  49.             else
  50.             {
  51.                 var memberExpression = unaryExpressionBody.Operand as MemberExpression;
  52.  
  53.                 if (memberExpression == null)
  54.                     throw new ArgumentException("Unable to determine operand of expression.", "func");
  55.  
  56.                 Selector = Expression.Lambda(memberExpression, func.Parameters);
  57.             }
  58.  
  59.             Direction = direction;
  60.         }
  61.  
  62.         public OrderDirection Direction { get; set; }
  63.         public LambdaExpression Selector { get; set; }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement