Use OrderBy to dynamically sort LINQ results
Question:
How to dynamically specify the parameters passed to the OrderBy method based on the parameters?
Details:
Suppose you have a list of students and want to sort them by a specific attribute. The current implementation uses hardcoded property names, but how do I pass property names as parameters?
Example:
<code class="language-C#">string param = "City"; List<student> orderByAddress = existingStudents.OrderByDescending(c => param).ToList();</code>
Solution:
The solution involves dynamically building expression trees using reflection. An extension method can be created as follows:
<code class="language-C#">public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, bool desc) { string command = desc ? "OrderByDescending" : "OrderBy"; var type = typeof(TEntity); var property = type.GetProperty(orderByProperty); var parameter = Expression.Parameter(type, "p"); var propertyAccess = Expression.MakeMemberAccess(parameter, property); var orderByExpression = Expression.Lambda(propertyAccess, parameter); var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExpression)); return source.Provider.CreateQuery<TEntity>(resultExpression); }</code>
orderByProperty
parameter represents the attribute name, and desc
determines the sorting order.
Usage:
You can now sort your student list dynamically:
<code class="language-C#">existingStudents.OrderBy("City", true); // 按城市降序排序 existingStudents.OrderBy("City", false); // 按城市升序排序</code>
The above is the detailed content of How to Dynamically Order LINQ Results Using OrderBy?. For more information, please follow other related articles on the PHP Chinese website!