如何动态添加降序到orderby?

时间:2015-06-21 06:06:31

标签: c# linq

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

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();

但是,如果需要按顺序降序(取决于UI中的用户选择),我将不得不构造另一个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;
        // ....
    }
}

我有没有办法动态地将降序关键字添加到查询中?

2 个答案:

答案 0 :(得分:2)

这不是很好,但 不好

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();

答案 1 :(得分:2)

假设:

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
}