tags:

views:

75

answers:

2

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?

+1  A: 

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")
Dave L
It worked! Kind of reminds me of SubSonic. What I don't like about it is that it only extends IQueryable so I in order to use it I will have to run .AsQueryable() on my collections.
adolfojp
+1  A: 

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.

James Black