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?
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.
This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.
You can get Dynamic Linq
through Nuget. Then you can use .OrderBy(sortby + " " + sortdirection)
.
Here is the link: Dynamic Linq.
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