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

  • Thread starter Thread starter Ilyas
  • Start date Start date
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?
 
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.
 
Back
Top