Use dynamic parameters to customize OrderBy expressions in LINQ
LINQ’s OrderBy extension method allows you to sort a collection of objects based on one or more properties. But how do you specify which properties to sort using the values passed in as parameters?
Background:
The following code shows basic usage of OrderBy, where the properties are hardcoded:
<code class="language-csharp">List<student> existingStudends = new List<student>{ new Student {...}, new Student {...}}; List<student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList();</code>
Dynamic attribute specification:
In order to dynamically specify the properties to be sorted, you can leverage reflection to build the necessary expression tree. Here is an extension method that implements this functionality:
<code class="language-csharp">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>
where orderByProperty
is the name of the property you want to sort and desc
determines whether to sort in descending order (true) or ascending order (false).
Usage:
Using this extension method you can now dynamically sort by any attribute:
<code class="language-csharp">string param = "City"; List<student> orderbyAddress = existingStudends.OrderBy("City", true).ToList(); // 按城市降序排序 List<student> orderbyName = existingStudends.OrderBy("Name", false).ToList(); // 按名称升序排序</code>
The above is the detailed content of How Can I Dynamically Specify the Sort Property in a LINQ OrderBy Clause?. For more information, please follow other related articles on the PHP Chinese website!