using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace CatalogSupport.Helper
{
    public class GenericSorter<T>
    {
        public IEnumerable<T> Sort(IEnumerable<T> source, SortingDescriptor sortingDescriptor)
        {
            var param = Expression.Parameter(typeof(T), "item");

            var sortExpression = Expression.Lambda<Func<T, object>>
            (Expression.Convert(Expression.Property(param, sortingDescriptor.SortMember), typeof(object)), param);

            if (sortingDescriptor.SortDirection == ListSortDirection.Ascending)
            {
                var ret = source.AsQueryable<T>();
                ret = ret.OrderBy<T, object>(sortExpression);

                return source.AsQueryable<T>().OrderBy<T, object>(sortExpression);
            }
            else
            {
                return source.AsQueryable<T>().OrderByDescending<T, object>(sortExpression);
            }
        }
    }
}