Short solution for short problems

.Net: using dynamic columns in orderby with LINQ

I have a LINQ query that uses dynamic order by columns. The web client passes an array of key value objects and based on these objects I want to order the LINQ query.

After some googling around I found that the System.Linq.Dynamic namespace has the solution to this!

Add the Linq.Dynamic using the nuget package manager.

Then add the namespace to your class:

using System.Linq.Dynamic;

Now I dynamically build the order by string:

string orderby = String.Join(", ", orderByList.Select(o => o.Key + " " + o.Value ));

For example the orderby string holds this value “SalesOrder DESC CustomerName DESC”. Next we just add the string to the orderby, because you added the namespace in your class, the extensions is available and you can pass a string to the orderby:

List<PlanOrders> lst = PlanEnts.PlanOrders.Where(p => (p.PlanStatus < 100)).OrderBy(orderby).ToList();