我必须通过列表查询,然后通过用户做出的选择对其进行排序。
用户可以有3个级别的订购。 (即:SortByItem1,SortByItem2,SortByItem3)
这就是我现在所拥有的。
// searchResult is IQueryable
if (SortByItem1 == null && SortByItem2 == null && SortByItem3 == null)
{
searchResult = searchResult.OrderBy(i => new { i.Name, i.Address }).ThenByDescending(i => i.CreatedDate);
}
else {
if(SortByItem1!=null)
{
if(SortByItem1=="Name") searchResult=searchResult.OrderBy(i=> i.Name);
else if(SortByItem1=="Date") searchResult=searchResult.OrderBy(i=> i.CreatedDate);
else if(SortByItem1=="Address") searchResult=searchResult.OrderBy(i=> i.Address);
}
if(SortByItem2!=null)
{
if(SortByItem2=="Name") searchResult=searchResult.OrderBy(i=> i.Name);
else if(SortByItem2=="Date") searchResult=searchResult.OrderBy(i=> i.CreatedDate);
else if(SortByItem2=="Address") searchResult=searchResult.OrderBy(i=> i.Address);
}
if(SortByItem3!=null)
{
if(SortByItem3=="Name") searchResult=searchResult.OrderBy(i=> i.Name);
else if(SortByItem3=="Date") searchResult=searchResult.OrderBy(i=> i.CreatedDate);
else if(SortByItem3=="Address") searchResult=searchResult.OrderBy(i=> i.Address);
}
}
如您所见,这不是一种可靠的订购方式。我想让ThenBy订购其他所有尾随订单。但编译器不允许简单地使用ThenBy而不是OrderBy。
如何在此处对记录使用多个排序?
答案 0 :(得分:2)
这是一个想法。您不必一直调用OrderBy
来定义排序表达式,而是一次调用OrderBy
和ThenBy
:
Expression<Func<SearchResultType, string>> first;
Expression<Func<SearchResultType, string>> second;
Expression<Func<SearchResultType, string>> third;
// determine which is which, assignment happens like this:
// first = i => i.Name;
searchResult = searchResult.OrderBy(first).ThenBy(second).ThenBy(third);
答案 1 :(得分:2)
对@ Andrei的答案的一个改进是将其包含在一个扩展方法中,你可以直接在任何IQueryable<T>
上调用它(这很容易为IEnumerable<T>
支持进行调整)
public static IQueryable<T> SortBy<T>(this IQueryable<T> src, params Expression<Func<T, object>>[] filters)
{
if (filters == null)
return src;
var result = src.OrderBy(filters.FirstOrDefault());
foreach (var f in filters.Skip(1))
{
result = result.ThenBy(f);
}
return result;
}
这将允许任意排序,例如
// sort by name then by address and finally by date
var sorted = items.SortBy(x => x.Name, x => x.Address, x => x.Date);
// sort by date then by address
var sorted = items.SortBy(x => x.Date, x => x.Address);
// sort by name only
var sorted = items.SortBy(x => x.Name);