我想优化以下几行代码进行排序。
public ViewResult Index(string sortorder, int? pagesize, int? page)
{
int pageSize = pagesize ?? 10;
if (Request.HttpMethod != "GET")
{
page = 1;
pageSize = 10;
}
ViewBag.SelectedPageSize = pageSize;
ViewBag.CurrentSort = sortorder;
ViewBag.FirstNameSortParm = String.IsNullOrEmpty(sortorder) ? "FirstName desc" : "";
ViewBag.LastNameSortParm = sortorder == "LastName" ? "LastName desc" : "LastName";
ViewBag.DepNameSortParm = sortorder == "depName" ? "depName desc" : "depName";
var joined = from tm in db.TabMasters select tm;
switch (sortorder)
{
case "FirstName":
joined = joined.OrderBy(m => m.FirstName);
break;
case "FirstName desc":
joined = joined.OrderByDescending(m => m.FirstName);
break;
case "LastName":
joined = joined.OrderBy(m => m.LastName);
break;
case "LastName desc":
joined = joined.OrderByDescending(m => m.LastName);
break;
case "depName":
joined = joined.OrderBy(m => m.depName);
break;
case "depName desc":
joined = joined.OrderByDescending(m => m.depName);
break;
default:
joined = joined.OrderBy(m => m.FirstName);
break;
}
int pageIndex = (page ?? 1) - 1;
int start = (pageIndex * pageSize);
ViewBag.TotalRecord = joined.Count();
ViewBag.StartRecord = start + 1;
ViewBag.EndRecord = ((start + pageSize) >= ViewBag.TotalRecord) ? ViewBag.TotalRecord : (start + pageSize);
return View(joined.ToPagedList(pageIndex, pageSize));
}
因为如果我有更多的10个字段来执行排序,这是非常繁琐的方式。
谢谢, Imdadhusen
答案 0 :(得分:1)
我的实际目标有点模糊,但对于切换部分,您可以使用扩展方法,如下所示。
public static class SortExtensions
{
public static IEnumerable<T> SortByField<T>(this IEnumerable<T> sequence, string sortOrder)
{
var tokens = sortOrder.Trim().Split(' ');
var field = tokens[0];
var direction = tokens.Skip(1).Single().ToLower();
var prop = typeof(T).GetProperty(field);
return direction == "desc"
? sequence.OrderByDescending(m => prop.GetValue(m, null))
: sequence.OrderBy(m => prop.GetValue(m, null));
}
}
它将对排序顺序进行非常简化的解析。它将责任放在主叫方上,这通常不是你想要做的,因此如果排序顺序字符串不符合要求,你可能需要一些错误处理。
你可以像这样使用它:
db.TabMasters.SortByField(sortOrder)
根据评论编辑:
在没有任何错误处理的情况下,行类型(T).GetProperty(字段)是脆弱的。它依赖于第一个标记作为类型T的公共属性的名称。如果名称与属性不匹配,它将返回null。包括它是否与Field名称匹配。获得FieldInfo的功能类似 prop.GetField(field)将返回一个fieldinfo对象,其中包含给定名称的公共字段,否则为null。要获取字段的值,只需省略GetValue调用的最后一个参数。
答案 1 :(得分:1)
你应该看看Linq.DynamicQuery。 此博文http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
中有更多信息该库允许您编写以下代码:
var query = northwind.Products
.Where("CategoryID = 3 AND UnitPrice > 3")
.OrderBy("SupplierID");
而不是
var query = from p in northwind.Products
where p.CategoryID == 3 && p.UnitPrice > 3
orderby p.SupplierID
select p;
如果要添加sortdirection:
var query = northwind.Products.OrderBy("SupplierID Descending");