如何在orderby中动态添加降序



我可以使用orderby语句动态构建LinqQuery,如下所示:

var Query = from q in Db.TblUsers select q;
switch (Order)
{
    case "Name": Query = from q in Query orderby q.Name select q; break;
    case "DOB": Query = from q in Query orderby q.DOB select q; break;
    // ... and more cases
}
var Result = Query.ToList();

然而,如果需要按降序排列(取决于用户界面中的用户选择),我将不得不构建另一个switch语句,复制所有情况,只为在orderby后面添加"descending"关键字。

示例:

if (ascending)
{
    switch (Order)
    {
        case "Name": Query = from q in Query orderby q.Name select q; break;
        // ....
    }
}
else
{
    switch (Order)
    {
        case "Name": Query = from q in Query orderby q.Name descending select q; break;
        // ....
    }
}

有没有一种方法可以让我在查询中动态添加降序关键字?

给定:

public static class OrderByEx
{
    public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, bool ascending)
    {
        if (ascending)
        {
            return source.OrderBy(keySelector);
        }
        return source.OrderByDescending(keySelector);
    }
}

您可以:

var Query = Db.TblUsers.AsQueryable();
switch (Order)
{
    case "Name": 
        Query = Query.OrderBy(q=>q.Name, ascending);
        break;
    case "DOB": 
        Query = Query.OrderBy(q=>q.DOB, ascending);
        break;
    // ... and more cases
}

这不太好,但也不是坏:

var Query = Db.TblUsers.AsQueryable();
switch (Order)
{
    case "Name": Query = ascending ? 
                     Query.OrderBy(q=>q.Name) : 
                     Query.OrderByDescending(q=>q.Name);
        break;
    case "DOB": Query = ascending ? 
                     Query.OrderBy(q=>q.DOB) : 
                     Query.OrderByDescending(q=>q.DOB);
        break;
    // ... and more cases
}
var Result = Query.ToList();

参见

  • 订购人
  • 按降序排序

相关内容

  • 没有找到相关文章

最新更新