Home > Backend Development > C++ > How to Dynamically Order LINQ Results Using OrderBy?

How to Dynamically Order LINQ Results Using OrderBy?

Mary-Kate Olsen
Release: 2025-01-10 11:47:42
Original
121 people have browsed it

How to Dynamically Order LINQ Results Using OrderBy?

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>
Copy after login

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>
Copy after login
The

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template