I'm trying to generate a LINQ OrderBy
clause using lambda expressions with an input of the column name of an entity as a string (in the "sortOn" variable below).
The code below works fine for a sortOn value like "Code" generating the lambda
p => p.Code
But I would also like to sort on a child entity, where the lambda might be
p => p.Category.Description
So in this instance, I would just like to set sortOn = "Category.Description" and have the correct lamdba expression generated.
Is this possible? Any suggestions about the best way to do this would be welcomed.
This code works fine for the simple case:
var param = Expression.Parameter(typeof (Product), "p");
var sortExpression = Expression.Lambda<Func<Product, object>>(
Expression.Property(param, sortOn), param);
if (sortAscending ?? true)
{
products = products.OrderBy(sortExpression);
}
else
{
products = products.OrderByDescending(sortExpression);
}
The use-case for this problem is displaying a grid of data and being able to sort the data, simply by passing the column name to be sorted on back to the server. I'd like to make the solution generic, but have started using a particular type (Product in the example) for now.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…