Lets suppose that I have the following simple query
var q =
from p in products
orderby p.ProductName descending
select p;
What would be the simplest and most straightforward way to specify the sort field and direction at runtime?
Lets suppose that I have the following simple query
var q =
from p in products
orderby p.ProductName descending
select p;
What would be the simplest and most straightforward way to specify the sort field and direction at runtime?
We've used the dynamic linq library before to do this. Here's a link to Scott Guthrie's blog where he describes it.
Basically you could alter the above query to look like this:
var q = db.Products
.OrderBy("ProductName Descending")
I did it with a switch statement. Here is a snippet, where I am going in ascending direction. In my url I passed in a parameter to determine the direction, and what to sort by.
if (sortDirection == "asc")
{
switch (sortCol)
{
case 1:
q = from f in q
orderby f.Id ascending
select f;
q is obviously the result of the original LINQ select.