linq 動態排序 order by

項目查詢數據庫使用的是linq 語法,但是後期須要用到不一樣字段的排序。
各類糾結! 在網上找了各類資料 後面才找到兩種方法



using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace Rose.Repository.Repositories { public static class DBHelper { public static IQueryable<T> DataSort<T>(IQueryable<T> source, string sortExpression, string sortDirection) { string sortingDir = string.Empty; if (sortDirection.ToUpper().Trim() == "ASC") sortingDir = "OrderBy"; else if (sortDirection.ToUpper().Trim() == "DESC") sortingDir = "OrderByDescending"; ParameterExpression param = Expression.Parameter(typeof(T), sortExpression); PropertyInfo pi = typeof(T).GetProperty(sortExpression); Type[] types = new Type[2]; types[0] = typeof(T); types[1] = pi.PropertyType; Expression expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, sortExpression), param)); IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr); return query; } public static IQueryable<T> DataPaging<T>(IQueryable<T> source, int pageNumber, int pageSize) { return source.Skip(pageNumber * pageSize).Take(pageSize); } public static IQueryable<T> Sorting<T>(IQueryable<T> source, string sortExpression, string sortDirection, int pageNumber, int pageSize) { IQueryable<T> query = DataSort<T>(source, sortExpression, sortDirection); return DataPaging(query, pageNumber, pageSize); } } } var list=from entity in db.Set<menu>() select entity;

 

2) System.Linq.Dynamic
開始我找了好久 System.Linq.Dynamic引用都沒用,最後使用的是數據庫

在nuget 中searh System.Linq.Dynamic 安裝對應的版本, 這樣均可以使用了ide

 var orderExpression = string.Format("{0} {1}", sortName, sortType); //sortName排序的名稱 sortType排序類型 (desc asc)
 return list.OrderBy(orderExpression).Skip(pageIndex).Take(pageSize).ToList();
相關文章
相關標籤/搜索