本文介绍了orderbydescending的动态linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mvc4 nuget包动态linq查询for orderby。我被困在这里。任何人都可以使用System.Linq.Dynamic帮助





;

public ActionResult Index(int? page,string sortOrder,string sortvarOrder)

{

ViewBag.NameSortParm = String.IsNullOrEmpty(sortvarOrder)? sortOrder_desc:sortOrder_asc;



int pageSize = 5;

int pageNumber =(page ?? 1);

var printerMaster = db.PrinterMasters.Include(x => x.WarehouseMaster);



if(sortOrder!= null)

{

if(ViewBag.NameSortParm == sortOrder_asc)

{

var result = db.PrinterMasters.OrderBy(sortOrder) .ToList();

返回视图(result.ToPagedList(pageNumber,pageSize));

}

else

{

var result1 = db.PrinterMasters.OrderByDescending(sortOrder)ToList();

返回View(result1.ToPagedList(pageNumber,pageSize));

}



}

其他

{

sortOrder =PrinterId;

var result = db.PrinterMasters.OrderBy(sortOrder).ToList();

返回View(result.ToPagedList(pageNumber,pageSize));

}

}



这个有用吗?我是mvc的新手。请帮助我

I am using mvc4 nuget package dynamic linq query for orderby. I was stuck at this. Can anyone help out Please


using System.Linq.Dynamic;
public ActionResult Index(int? page, string sortOrder,string sortvarOrder)
{
ViewBag.NameSortParm = String.IsNullOrEmpty(sortvarOrder) ? "sortOrder_desc":"sortOrder_asc";

int pageSize = 5;
int pageNumber = (page ?? 1);
var printerMaster = db.PrinterMasters.Include(x => x.WarehouseMaster);

if (sortOrder != null)
{
if (ViewBag.NameSortParm == sortOrder_asc)
{
var result = db.PrinterMasters.OrderBy(sortOrder).ToList();
return View(result.ToPagedList(pageNumber, pageSize));
}
else
{
var result1 = db.PrinterMasters.OrderByDescending(sortOrder)ToList();
return View(result1.ToPagedList(pageNumber, pageSize));
}

}
else
{
sortOrder = "PrinterId";
var result = db.PrinterMasters.OrderBy(sortOrder).ToList();
return View(result.ToPagedList(pageNumber, pageSize));
}
}

will this work?? I am new to mvc. Please help me

推荐答案

create an extension method as below

 public static class SortingExtension
    {
      public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
      {
          var param = Expression.Parameter(typeof(T), "p");
          var prop = Expression.Property(param, SortField);
          var exp = Expression.Lambda(prop, param);
          string method = Ascending ? "OrderBy" : "OrderByDescending";
          Type[] types = new Type[] { q.ElementType, exp.Body.Type };
          var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
          return q.Provider.CreateQuery<T>(mce);
      }
    }


//Do the following changes in the Action To the QueryField pass the column_Name to sortBy and the true/false value if true it will sort by Ascending for false Descending

var printerMaster = db.PrinterMasters.Include(x => x.WarehouseMaster);

printerMaster.OrderByField(fieldName,true)



这篇关于orderbydescending的动态linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 06:45