扩展方法 分页数据

    static class ListReturnPagingObjectExtension
    {
        static public object Paging<T>(this IEnumerable <T> l, NameValueCollection form)
        {
            if(!(l is IQueryable<T>) && !(l is IList<T>))
            l = l.ToList();
            var ql = l.AsQueryable();
            try
            {
                var input = new
                                {
                                    Skip = int.Parse(form["start"]),
                                    Count = int.Parse(form["limit"]),
                                    OrderBy = new Func<IQueryable<T>, IQueryable<T>>(q =>
                                                  {
                                                      var sort = form["sort"];
                                                      var dir = form["dir"] ?? "ASC";
                                                      if(string.IsNullOrEmpty(sort) || (dir != "ASC" && dir != "DESC"))
                                                        return q;
                                                      var paramExpr = Expression.Parameter(typeof(T), "item");
                                                      var ksExpr = Expression.Lambda(Expression.Property(paramExpr, sort), paramExpr);
                                                      var types = new [] { ql.ElementType, ksExpr.Body.Type };
                                                      var mce = Expression.Call(typeof(Queryable), dir == "ASC" ?
                                                          "OrderBy" : "OrderByDescending", types, ql.Expression, ksExpr);
                                                      return (IQueryable<T>) ql.Provider.CreateQuery(mce);
                                                  })
                };
                var output = new
                {
                    Data = input.OrderBy(ql).Skip(input.Skip).Take(input.Count),
                    Count = ql.Count(),
                };
                return output;

            }
            catch
            {
                if (form["start"] != null && form["limit"] != null)
                {
                    var skip = int.Parse(form["start"]);
                    var count = int.Parse(form["limit"]);
                    var output = new
                    {
                        Data = l.ToList().Skip(skip).Take(count),
                        Count = l.Count()
                    };
                    return output;
                }
                else
                {
                    return l.ToList();
                }
            }
        }
    }

你可能感兴趣的:(分页)