如何使用LINQ动态在MVC4? [英] How to use Dynamic LINQ in MVC4?

查看:140
本文介绍了如何使用LINQ动态在MVC4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从我的MVC4应用程序的查看的默认操作。

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

其中, modRes 是一个模型类,

我想用排序列,sortDir和页面参数在动态LINQ得出的结果。

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

任何帮助将是AP preciated。

Any help would be appreciated.

推荐答案

您可以使用此code为分页和排序数据:

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

此外,你应该不叫了ToList 方法上的 modRes.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.

这篇关于如何使用LINQ动态在MVC4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆