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?
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With