Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq orderby using property name string

Tags:

c#

sorting

linq

I have a list which I need to order eg.

var list = someelements;

I also have a parameter which says by which property and what direction I should order list data eg.

var sortby = "Name";
var sortdirection = "desc";

I was wondering if I can match string property name with the right property so I get:

var list = someelements.OrderBy(x => x.Name).ToList();

when sortby == "Name" without the need of using switch loop to check property name and assign a correct property to OrderBy.

Same I would like to achieve with select either OrderBy or OrderByDescending depending whether I get sortdirection = "asc" or sortdirection = "desc"

Is it possible and if yes, how?

like image 733
nickornotto Avatar asked Nov 30 '15 16:11

nickornotto


People also ask

What is OrderBy in Linq?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

Is Linq OrderBy stable?

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.


1 Answers

You can get Dynamic Linq through Nuget. Then you can use .OrderBy(sortby + " " + sortdirection). Here is the link: Dynamic Linq.

like image 83
Aleksa Avatar answered Oct 26 '22 22:10

Aleksa