IQueryable<T>
IEnumerable<T>
When using linq, you often sort the results set. Linq provides and data sources, not OrderBy
data sources. OrderByDescending
IQueryable<T>
To sort the data source, you need to use the IEnumerable<T>
method to convert it to
or IEnumerable<T>
method. However, converting to is not always feasible or efficient. AsQueryable
IQueryable<T>
Implement Orderby OrderBy
OrderByDescending
The following code fragment provides the implementation of the IQueryable<T>
data source
IEnumerable<T>
This implementation is divided into the specified attribute path into a single attribute name, and a reflection is used to generate an expression tree. This expression tree can be used to dynamically create IEnumerable<T>
or OrderBy
expressions. OrderByDescending
public static IOrderedEnumerable<T> OrderBy<T>( this IEnumerable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderBy"); } public static IOrderedEnumerable<T> OrderByDescending<T>( this IEnumerable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderByDescending"); } static IOrderedEnumerable<T> ApplyOrder<T>( IEnumerable<T> source, string property, string methodName) { // 此处省略部分代码,因为原代码不完整且存在错误,无法直接运行。需要补充完整的代码逻辑才能实现动态排序。 }
In order to further enhance the function, you can integrate this with dynamic Linq, which allows you to specify the sorting expression as a string similar to SQL. This is an example: <>
OrderBy
OrderByDescending
In this example,
Class provides an efficient cache and lock mechanism to ensure that the attribute accessor is created only once.
public static IOrderedEnumerable<dynamic> OrderBy( this IEnumerable<dynamic> source, string property) { return Enumerable.OrderBy<dynamic>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); } public static IOrderedEnumerable<dynamic> OrderByDescending( this IEnumerable<dynamic> source, string property) { return Enumerable.OrderByDescending<dynamic>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); }
The above is the detailed content of How to Implement Dynamic LINQ OrderBy on `IQueryable` and `IEnumerable`?. For more information, please follow other related articles on the PHP Chinese website!