项目查询数据库使用的是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;
- var str = DBHelper.DataSort(list, "menu_id", "desc");
(2) System.Linq.Dynamic
开始我找了很久 System.Linq.Dynamic引用都没用,最后使用的是
在nuget 中searh System.Linq.Dynamic 安装对应的版本, 这样都可以使用了
- var orderExpression = string.Format("{0} {1}", sortName, sortType); //sortName排序的名称 sortType排序类型 (desc asc)
- return list.OrderBy(orderExpression).Skip(pageIndex).Take(pageSize).ToList();
个人觉得使用System.Linq.Dynamic更加方便
|