51 lines
1.7 KiB
C#
51 lines
1.7 KiB
C#
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<TItem>(IQueryable<TItem> query)
|
|
{
|
|
return typeof(TItem).IsAssignableTo(typeof(ISortable));
|
|
}
|
|
|
|
public IQueryable<TItem> Sort<TItem>(IQueryable<TItem> 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<TItem>(propertyInfo);
|
|
|
|
return (sorting.SortDirection == SortingDirections.Ascending
|
|
? query.OrderBy(sortExpression)
|
|
: query.OrderByDescending(sortExpression))
|
|
.AsQueryable();
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Methods
|
|
|
|
private static Expression<Func<TItem, object>> CreateSortExpression<TItem>(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<Func<TItem, object>>(convertExpression, parameterExpression);
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|