前言
最近在给大家写一套开源的.net core权限管理框架。现在已经写到前台UI + 后台动态查询的部分。
发现需要动态orderby但是网上没有现成的例子
二话不说上代码
建议namespace
System.Linq.Dynamic
主体代码
/// <summary> /// 排序 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="query"></param> /// <param name="Field"></param> /// <param name="orderby"></param> /// <returns></returns> public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string Field, string orderby = "orderb") { if (!string.IsNullOrEmpty(Field)) { ParameterExpression p = Expression.Parameter(typeof(T)); Expression key = Expression.Property(p, Field); var propInfo = GetPropertyInfo(typeof(T), Field); var expr = GetOrderExpression(typeof(T), propInfo); if (!("desc" == orderby)) { var method = typeof(Queryable).GetMethods().FirstOrDefault(m => m.Name == "OrderBy" && m.GetParameters().Length == 2); var genericMethod = method.MakeGenericMethod(typeof(T), propInfo.PropertyType); return (IQueryable<T>)genericMethod.Invoke(null, new object[] { query, expr }); } else { var method = typeof(Queryable).GetMethods().FirstOrDefault(m => m.Name == "OrderByDescending" && m.GetParameters().Length == 2); var genericMethod = method.MakeGenericMethod(typeof(T), propInfo.PropertyType); return (IQueryable<T>)genericMethod.Invoke(null, new object[] { query, expr }); } } return query; } /// <summary> /// 获取反射 /// </summary> /// <param name="objType"></param> /// <param name="name"></param> /// <returns></returns> private static PropertyInfo GetPropertyInfo(Type objType, string name) { var properties = objType.GetProperties(); var matchedProperty = properties.FirstOrDefault(p => p.Name == name); if (matchedProperty == null) throw new ArgumentException("name"); return matchedProperty; } /// <summary> /// 获取生成表达式 /// </summary> /// <param name="objType"></param> /// <param name="pi"></param> /// <returns></returns> private static LambdaExpression GetOrderExpression(Type objType, PropertyInfo pi) { var paramExpr = Expression.Parameter(objType); var propAccess = Expression.PropertyOrField(paramExpr, pi.Name); var expr = Expression.Lambda(propAccess, paramExpr); return expr; }
写在最后
如果您觉着我的文章对您有用麻烦各位大佬点个赞点个关注
然后呢 刚刚创建了一个.net core的群欢迎大家进入:
点击链接加入群聊【.Net Core研究团】:https://jq.qq.com/?_wv=1027&k=5IEolkJ
然后集资创建一个网络社区。欢迎各位一起集资。