Dynamic specification of LINQ OrderBy parameters
In scenarios where you need to dynamically specify the fields used in the LINQ OrderBy operation, you can use reflection technology to achieve this.
Example:
Suppose there is a list of students existingStudents
and a parameter param
representing the field to be sorted.
List<student> existingStudents = new List<student> { ... }; string param = "City";
Standard implementation:
The default method calls OrderBy with a hard-coded property name for sorting:
List<student> orderedByAddress = existingStudents.OrderBy(c => c.Address).ToList();
Dynamic implementation:
Using reflection, you can create a dynamic expression:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string orderByProperty, bool desc) { // 确定排序表达式 string command = desc ? "OrderByDescending" : "OrderBy"; var type = typeof(T); 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<T>(resultExpression); }
Usage:
It is now possible to dynamically order by any attribute using the OrderBy extension method:
List<student> orderbyAddress = existingStudents.OrderBy("City", true); // 降序 List<student> orderbyName = existingStudents.OrderBy("Name", false); // 升序
The above is the detailed content of How Can I Dynamically Specify the OrderBy Field in LINQ?. For more information, please follow other related articles on the PHP Chinese website!