How to specify sort field and direction in linq query at runtime?

Suppose I have the following simple query

var q = 
    from p in products
    orderby p.ProductName descending
    select p;

      

What would be the easiest and easiest way to specify the field and direction of the sort at runtime?

+1


a source to share


2 answers


We used the linq dynamic link library before doing this. Here's a link to Scott Guthrie's blog where he describes it.

Basically you can change the above query like this:



var q = db.Products
        .OrderBy("ProductName Descending")

      

+1


a source


I did it with a switch statement. Here is a snippet where I am going in an upward direction. In my url, I passed in a parameter to determine the direction and what to sort.

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 choice.

+1


a source







All Articles