drinu16
drinu16

Reputation: 795

Sorting in Linq by constructing the linq statement as a string?

The user have the option to sort by price or by date listed. Both can be sorted in ascending or descending. They both can be used or one of them.

What is the best practical method to use in such a situation ?

Can I make 1 linq statement and replace the words "ascending"/"descending" or remove them from the statement by modifying a string ? (in other words, construct the linq statement like sql?)

Upvotes: 0

Views: 62

Answers (2)

DGibbs
DGibbs

Reputation: 14608

Instead of relying on strings, you can use the SortOrder enum:

public MyCollection OrderedByPrice(SortOrder sortOrder)
{
     if (sortOrder == SortOrder.Ascending)
     {
         return new MyCollection(this.OrderBy(x => x.Price));
     }
     else
     {
         return new MyCollection(this.OrderByDescending(x => x.Price));
     }
}

As per your comments, if you want to order by both you could use ThenBy

public MyCollection OrderedByPriceThenByDate(SortOrder sortOrder)
{
     if (sortOrder == SortOrder.Ascending)
     {
         return new MyCollection(this.OrderBy(x => x.Price)
                                .ThenBy(y => y.Date));
     }
     else
     {
         return new MyCollection(this.OrderByDescending(x => x.Price)
                                .ThenByDescending(y => y.Date));
     }
}

Upvotes: 1

COLD TOLD
COLD TOLD

Reputation: 13569

you can also build an expression to do it

public IEnumerable<T> ExecuteSort<T>(
   IQueryable<T> src, Expression<Func<T,bool>> predicate, SortOrder sortOrder)
{
     if (sortOrder == SortOrder.Ascending)
     {
         return src.OrderBy(predicate));
     }
     else
     {
         return src..OrderByDescending(predicate));
     }
}

ExecuteSort(src, v => v.Price, ortOrder.Ascending); 

Upvotes: 1

Related Questions