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?
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?