using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using GerstITS.Common; using GerstITS.Search; namespace GerstITS.Examples.Logic.Shared.Search.Sorting { internal class SortingProvider : ISortingProvider { #region ISortingProvider public bool CanSort(IQueryable query) { return typeof(TItem).IsAssignableTo(typeof(ISortable)); } public IQueryable Sort(IQueryable query, ISorting sorting) { var propertyInfo = typeof(TItem).GetProperties() .SingleOrDefault(i => string.Equals(i.Name, sorting.SortBy, StringComparison.InvariantCultureIgnoreCase)); if (!CanSort(query) || propertyInfo.IsNull()) return query; var sortExpression = CreateSortExpression(propertyInfo); return (sorting.SortDirection == SortingDirections.Ascending ? query.OrderBy(sortExpression) : query.OrderByDescending(sortExpression)) .AsQueryable(); } #endregion #region Methods private static Expression> CreateSortExpression(MemberInfo propertyInfo) { var parameterExpression = Expression.Parameter(typeof(TItem), "x"); var propertyExpression = Expression.Property(parameterExpression, propertyInfo.Name); var convertExpression = Expression.Convert(propertyExpression, typeof(object)); return Expression.Lambda>(convertExpression, parameterExpression); } #endregion } }