dotnet + LinQ 按照指定的字段 和 排序方式排序

 1  /// <summary>
 2         /// 根据指定属性名称对序列进行排序
 3         /// </summary>
 4         /// <typeparam name="TSource">source中的元素的类型</typeparam>
 5         /// <param name="source">一个要排序的值序列</param>
 6         /// <param name="property">属性名称</param>
 7         /// <param name="descending">是否降序</param>
 8         /// <returns></returns>
 9         public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string property, bool descending) where TSource : class
10         {
11             ParameterExpression param = Expression.Parameter(typeof(TSource), "c");
12             PropertyInfo pi = typeof(TSource).GetProperty(property);
13             MemberExpression selector = Expression.MakeMemberAccess(param, pi);
14             LambdaExpression le = Expression.Lambda(selector, param);
15             string methodName = (descending) ? "OrderByDescending" : "OrderBy";
16             MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[] { typeof(TSource), pi.PropertyType }, source.Expression, le);
17             return source.Provider.CreateQuery<TSource>(resultExp);

 

 items = SortLinQUtil.OrderBy(items, param.orderName, true);

posted @ 2019-08-15 17:10  ccsoft  阅读(1445)  评论(0编辑  收藏  举报