using System.Linq.Expressions; namespace BaseOUDAL { public static class BllExtension { public static SearchListResult ToSearchList(this IQueryable query, BaseSearchReq req, bool isWithOrder = true) { if (req.rows == 0) { req.rows = 100000; req.page = 1; } if (req.page <= 0) { req.page = 1; } if (isWithOrder) { if (req.sidx != null) { var sidx = req.sidx.Split(',').ToList(); var anotherLevel = false; sidx.ForEach(t => { query = OrderingHelper(query, t.Trim(), req.sord == "desc", anotherLevel); anotherLevel = true; }); } } var retListResult = new SearchListResult { records = query.Count(), rows = query.Skip((req.page - 1) * req.rows).Take(req.rows).ToList(), page = req.page }; retListResult.total = (retListResult.records - 1) / req.rows + 1; return retListResult; } static IOrderedQueryable OrderingHelper(IQueryable source, string propertyName, bool descending, bool anotherLevel) { var param = Expression.Parameter(typeof(T), string.Empty); // I don't care about some naming var propNameArray = propertyName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); MemberExpression property = null; foreach (var propName in propNameArray) { if (property == null) { property = Expression.PropertyOrField(param, propName); } else { property = Expression.PropertyOrField(property, propName); } } var sort = Expression.Lambda(property, param); var call = Expression.Call( typeof(Queryable), (!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty), new[] { typeof(T), property.Type }, source.Expression, Expression.Quote(sort)); return (IOrderedQueryable)source.Provider.CreateQuery(call); } } }