How to order by a variable column name using linq??

I

Ilyas

How do I order by a variabe column name using linq

For example I have the following code:

public List<Product> GetPaged(int startRowIndex, int
maximumRows, string sortExpression)
{
NorthwindDataContext context = new NorthwindDataContext();
context.DeferredLoadingEnabled = false;
var query = context.Products.OrderBy(x=>x.ProductID);
switch (sortExpression.ToLower())
{
case "productid":
query = query.OrderBy(x => x.ProductID);
break;
case "productname":
query = query.OrderBy(x => x.ProductName);
break;
}
return
query.Skip(startRowIndex).Take(maximumRows).ToList();
}

However I also have about 8 other fields which I can order by, do I
have to repeat them in the case statement. Surly there is a better
way?
 
A

Andrus

Marc has published great dynamic orderby samples in this group which I use
and which work with IQueryable<T>

MS Dynamic Linq Library has dynamic order by code which works only with
non-generic IQueryable.
You can also create linq statement using string builder, compile and execute
it dynamically.

Andrus.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top