Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add descending to orderby?

Tags:

c#

linq

I can construct Linq Query dynamically with orderby statement like below:

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

However, if there is a need to be ordered descending (depends on user selection in the UI), I will have to construct another switch statement duplicate all the cases just to add the "descending" keyword after the orderby.

example:

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;
        // ....
    }
}

Is there a way for me to add just the descending keyword dynamically to the query?

like image 258
s k Avatar asked Jun 21 '15 06:06

s k


2 Answers

It's not great, but it's not that bad:

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

See

  • OrderBy
  • OrderByDescending
like image 140
John Saunders Avatar answered Oct 06 '22 00:10

John Saunders


Given:

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

You can:

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
}
like image 39
xanatos Avatar answered Oct 06 '22 01:10

xanatos