Linq Order when the column name is dynamic and passed as a string to a function

I have a Linq query (Entity Framework) as

function getData(string col_to_sort , bool IsAscending , int pageNo , int pageSize)
{
  context.table_name.Skip(pageNo*pageSize).Take(pageSize).ToArray();
}

I want that if I pass the column name as a function parameter and the order will sort my query too.

Since my column name will be a string, so we may need to convert it to ObjectQuery.

How can i achieve this?

Any help is appreciated.

+5
source share
1 answer

You can use Dynamic Linq :

string direction = IsAscending ? " ASC" : " DESC";
context.table_name.OrderBy(col_to_sort + direction).Skip(pageNo*pageSize).Take(pageSize).ToArray();
+6
source

All Articles