0

This is the default action from the "View" of my MVC4 application.

public ActionResult Index(string sort = "R_ResDate", 
                          string sortdir = "DESC", 
                          int page = 1)
{
    List<Result> results = modRes.Results.ToList();

    var results = from r in results
                  orderby r.R_ResultDate descending
                  select r;

    return View(results);
}

Where modRes is a Model class,

I wanted to use the sort column, sortDir, and page arguments in the dynamic linq to derive the results.

Any help would be appreciated.

alexmac
  • 19,087
  • 7
  • 58
  • 69
  • The dynamic link tag you've added to this post has, in it's info this link : http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx Maybe give it a shot and see where it goes. Update this post with your findings. – gideon Feb 25 '14 at 05:39

1 Answers1

-1

You can use this code for paging and sorting data:

var p = Expression.Parameter(typeof(Model));
var sortByFunc = Expression.Lambda<Func<Model, object>>(Expression.TypeAs(Expression.Property(p, sortByKey), typeof(object)), p).Compile();

var items = from r in modRes.Results
            orderby r.R_ResultDate descending
            select r;
var orderedItems = sortByAsc 
      ? items.OrderBy(sortByFunc) 
      : items.OrderByDescending(sortByFunc);
var results = orderedItems.Skip((pageIndex - 1) * pageSize).Take(pageSize);

return View(results);

Also, you shouldn't to call ToList method on modRes.Results query, because in this case will be loaded all data, when only data for one page should be loaded.

alexmac
  • 19,087
  • 7
  • 58
  • 69
  • I had used _sortByFunc_ earlier, but didn't use boxing with that. Thanks. –  Feb 25 '14 at 06:17