How to dynamically add a descent to orderby?

I can build Linq Query dynamically with an orderby statement, as shown 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 sort in descending order (it depends on the user choice in the user interface), I will have to build another switch statement in order to duplicate all cases in order to add a β€œdescending” keyword after 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 to add a dynamic expression for a top-down keyword in a query?

+6
source share
3 answers

This is not great, but it is not so 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(); 

Cm

+2
source

Try to consider dynamic Linq. It seems to me that this is easier for your solution http://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library

+1
source

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 } 
+1
source

Source: https://habr.com/ru/post/989464/


All Articles