如何根据记录动态排序

本文关键字:动态 排序 记录 何根 | 更新日期: 2023-09-27 17:50:52

我有以下索引操作方法,显示对象列表如下:-

public ActionResult Index(string searchTerm = "", int page = 1)
        {
            string withOutSpace = searchTerm.Trim();
            ViewBag.searchTerm = searchTerm;
            int pagesize;
            bool succeed = int.TryParse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"], out pagesize);
            var racks = repository.AllFind(withOutSpace).OrderBy(a => a.Technology.SerialNumber).ToPagedList(page, pagesize);

目前我总是按SerialNumber排序,但我的问题是如何将参数传递给我的索引动作方法,并根据传递的参数(如价格、日期等)进行排序。有人能给点建议吗?第二个问题,我怎么能第一次调用顺序是升序而第二次调用顺序是降序?由于

如何根据记录动态排序

public ActionResult Index(string searchTerm = "", string sort, bool asc, int page = 1)
{
    string withOutSpace = searchTerm.Trim();
    ViewBag.searchTerm = searchTerm;
    int pagesize;
    bool succeed = int.TryParse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"], out pagesize);
    var racks = repository.AllFind(withOutSpace);
    if(asc)
    {
        switch(sort)
        {
            case "price":
                racks = racks.OrderBy(a => a.Technology.Price);
                break;
            case "date":
                racks = racks.OrderBy(a => a.Technology.Date);
                break;
            case default:
                racks = racks.OrderBy(a => a.Technology.SerialNumber);
                break;
        }
    }
    else
    {
        switch(sort)
        {
            case "price":
                racks = racks.OrderByDescending(a => a.Technology.Price);
                break;
            case "date":
                racks = racks.OrderByDescending(a => a.Technology.Date);
                break;
            case default:
                racks = racks.OrderByDescending(a => a.Technology.SerialNumber);
                break;
        }
    }
    racks = racks.ToPagedList(page, pagesize)

你可以在orderBymethod中使用反射,比如

racks.OrderBy(a => { 
                        //use reflection get the property
                        PropInfo prop = a.GetType().GetProperty("price");
                        return prop;
                   })

我还没有测试过这段代码,这只是一个想法