Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Order by when column name is dynamic and pass as a string to a function

I have a Linq (Entity Framework) Query as

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

What i want is that if i pass the name of the column as a parameter to the function and the order it will sort my query too.

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

How can i achieve this?

Any help is appreciated

like image 602
Moons Avatar asked Dec 06 '11 10:12

Moons


1 Answers

You can use Dynamic Linq:

string direction = IsAscending ? " ASC" : " DESC";
context.table_name.OrderBy(col_to_sort + direction).Skip(pageNo*pageSize).Take(pageSize).ToArray();
like image 69
Thomas Levesque Avatar answered Nov 12 '22 11:11

Thomas Levesque