6

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
s k
  • 4,342
  • 3
  • 42
  • 61
  • 3
    http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet – Y.S Jun 21 '15 at 06:09
  • Maybe you can just use `if (!ascending) { Query = Query.Reverse(); }`? Or you could wait until you have your `List<>` which can be reversed in-place: `Result.Reverse();` – Jeppe Stig Nielsen Jun 21 '15 at 06:34
  • Try to consider Dynamic Linq I think it's easier for your solution http://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library – Wahid Bitar Jun 21 '15 at 10:10

2 Answers2

3

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
}
xanatos
  • 109,618
  • 12
  • 197
  • 280
2

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397