Reputation: 3823
I have implemented custom paging in my .NET MVC application as you can see in down below code:
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int totalRecords = 0;
using (var ctx = new myContext())
{
var v = ctx.zsp_select_allusers().ToList();
if(!string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir))
{
v = v.OrderBy(sortColumn + " " + sortColumnDir);
}
totalRecords = v.Count();
var data = v.Skip(skip).Take(pageSize).ToList();
return Json(new { draw=draw, recordsFiltered = totalRecords, recordsTotal = totalRecords, data = data },JsonRequestBehavior.AllowGet);
}
Implemented custom paging works fine but I'm getting an error on this line of code:
v = v.OrderBy(sortColumn + " " + sortColumnDir);
where it says:
the type argument for method Enumerable.OrderBy(... )cannot be inferred
What am I doing wrong here?
Upvotes: 0
Views: 1057
Reputation: 156624
With the LINQ operators provided by the .NET baked-in libraries, you would need to construct an Expression<Func<,>>
to pass into either OrderBy
or OrderByDescending
.
For building dynamic queries based on strings provided at runtime, you should probably look at a library like DynamicLinq
, which will allow you to sort by a string like "someColumnName descending"
.
Upvotes: 1
Reputation: 951
As Will mentioned, OrderBy
takes a Func<T,R>
for its parameter - assuming that your list of users in v
(which is a fairly bad variable name, btw), has properties called name and dir, you could do:
v.OrderBy(x => x.name).ThenBy(x => x.dir)
Upvotes: 1