public static IOrderedEnumerable <T> SortBy <T, TKey>( this IEnumerable <T> source, IEnumerable <Sort> sort, Func <T, TKey> defaultSort, SortDirection defaultSortDirection = SortDirection.Asc) { IEnumerable <T> source1 = source; List <Sort> scrubbedSortList = SortByExtensions.GetScrubbedSortList <T>(sort); if (!scrubbedSortList.Any <Sort>()) { if (defaultSortDirection != SortDirection.Desc) { return(source1.OrderBy <T, TKey>(defaultSort)); } return(source1.OrderByDescending <T, TKey>(defaultSort)); } for (int index = 0; index < scrubbedSortList.Count; ++index) { Sort sort1 = scrubbedSortList[index]; ParameterExpression parameterExpression = null; Func <T, object> keySelector = Expression.Lambda <Func <T, object> >((Expression)Expression.Convert((Expression)Expression.Property((Expression)parameterExpression, sort1.Name), typeof(object)), parameterExpression).Compile(); source1 = index != 0 ? (sort1.Direction == SortDirection.Desc ? (IEnumerable <T>)((IOrderedEnumerable <T>)source1).ThenByDescending <T, object>(keySelector) : (IEnumerable <T>)((IOrderedEnumerable <T>)source1).ThenBy <T, object>(keySelector)) : (sort1.Direction == SortDirection.Desc ? (IEnumerable <T>)source1.OrderByDescending <T, object>(keySelector) : (IEnumerable <T>)source1.OrderBy <T, object>(keySelector)); } return((IOrderedEnumerable <T>)source1); }
public static IOrderedQueryable <T> SortBy <T, TKey>( this IQueryable <T> source, IEnumerable <Sort> sort, Expression <Func <T, TKey> > defaultSort, SortDirection defaultSortDirection = SortDirection.Asc) { IOrderedQueryable <T> source1 = (IOrderedQueryable <T>)source; List <Sort> scrubbedSortList = SortByExtensions.GetScrubbedSortList <T>(sort); if (!scrubbedSortList.Any <Sort>()) { if (defaultSortDirection != SortDirection.Desc) { return(source1.OrderBy <T, TKey>(defaultSort)); } return(source1.OrderByDescending <T, TKey>(defaultSort)); } for (int index = 0; index < scrubbedSortList.Count; ++index) { Sort sort1 = scrubbedSortList[index]; string keyword = (index == 0 ? "OrderBy" : "ThenBy") + (sort1.Direction == SortDirection.Desc ? "Descending" : string.Empty); source1 = source1.SortOrderedQueryableBy <T>(sort1.Name, keyword); } return(source1); }