public static IQueryable <T> Filter <T>(IQueryable <T> items, FilterAndSortingOptions options) { if (options != null) { List <FilterMetaRecord> filtersForCurrentType = list.GetFiltersForCurrentType(items.ElementType); foreach (var f in options.Filters) { if (f.Value != null && f.Value.Count > 0) { var now_meta = filtersForCurrentType.FirstOrDefault(j => j.Name == f.Field); if (now_meta != null) { if (!(now_meta.ParametrType != typeof(string) && (f.Value[0] == null || f.Value[0] == ""))) { items = FilterByFilterMetaRecord(items, f, now_meta); } } } } if (options.Sortings != null && options.Sortings.Count > 0) { var orderList = options.Sortings.Where(j => filtersForCurrentType.FirstOrDefault(i => i.Name == j.Field) != null).OrderBy(j => j.Priority).ToList(); if (orderList.Count > 0) { var orderedItems = SortingBySortingMetaRecord <T>(items, orderList[0], filtersForCurrentType.First(j => j.Name == orderList[0].Field)); for (int i = 1; i < orderList.Count; i++) { orderedItems = ThenSortingBySortingMetaRecord <T>(orderedItems, orderList[i], filtersForCurrentType.First(j => j.Name == orderList[i].Field)); } items = orderedItems; } } else { var defaultFilter = filtersForCurrentType.First(j => j.Name == "Default"); var defultSorting = new SortingRecord() { Direction = defaultFilter.DefaultSorting.ToString(), Field = "Default", Priority = 1 }; items = SortingBySortingMetaRecord <T>(items, defultSorting, defaultFilter); } } return(items); }
public static IOrderedQueryable <T> ThenSortingBySortingMetaRecord <T>(IOrderedQueryable <T> items, SortingRecord sort, FilterMetaRecord meta) { var param = Expression.Parameter(typeof(T), "x"); var propertyAccess = meta.Path.Split('.').Aggregate((Expression)param, Expression.Property); if (sort.Direction == "asc") { return((IOrderedQueryable <T>)items.Provider.CreateQuery(Expression.Call(typeof(Queryable), "ThenBy", new Type[] { typeof(T), meta.ParametrType }, items.Expression, Expression.Lambda(propertyAccess, param)))); } else { return((IOrderedQueryable <T>)items.Provider.CreateQuery(Expression.Call(typeof(Queryable), "ThenByDescending", new Type[] { typeof(T), meta.ParametrType }, items.Expression, Expression.Lambda(propertyAccess, param)))); } }