C#技术百科
问问你的心你有没有信心 做事情要专一坚定,执着

    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();
                }
            }
        }
    }

posted on 2011-06-30 09:16  王德田  阅读(360)  评论(0编辑  收藏  举报