Search code examples
c#linqsortingpagination

Entity IQueryable with page, search and sort


I'm sure this has been answered before, but can't seem to find it.

I'm looking for a simple download (or tutorial) for building an IQueryable that can be sorted, paged and searched.

e.g.

IQueryable<T> myThings , params[] searchKeyValuePairs, params[] orderKeyValuePairs, int pageSize, int pageNumber

Or something similar. Guessing it will be using Dynamic Linq.

My requirement is for a number of MVC3 views for broadly similar data. BA specified about 20 views of each of 10 data types...but MOST of these views are simply "All Today" and "Sorted by Cost" type views.

Data is from SQL or Oracle through EF4.


Solution

  • For paging:

    public class PagingList<T> : List<T>
    {
        public int PageIndex { get; set; }
        public int PageSize { get; set; }
        public int TotalCount { get; set; }
        public int TotalPages { get; set; }
        public string pagerange { get; set; }
        public int pagingrange { get; set; }
    
        public PagingList(IQueryable<T> data, int page, int pagesize)
        {
            PageIndex = page;
            PageSize = pagesize;
            TotalCount = data.Count();
            TotalPages = (int)Math.Ceiling(TotalCount /(double)PageSize);
    
            this.AddRange(data.Skip(PageIndex * PageSize).Take(PageSize));
    
        }
        //public void GeneratePageRange()
        //{
        //    for (int i = 1; i <= TotalPages; i++)
        //    {
        //        pagingrange = i
        //    }
        //}
        public bool HasPreviousPage
        {
            get { return (PageIndex > 0); }
        }
    
        public bool HasNextPage
        {
            get { return (PageIndex + 1 < TotalPages); }
        }
    }