Csharp/C#教程:为通用列表创建排序函数分享


为通用列表创建排序函数

我有一个按对象字段排序通用列表的方法:

public static IQueryable SortTable(IQueryable q, string sortfield, bool ascending) { var p = Expression.Parameter(typeof(T), "p"); if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int?)) { var x = Expression.Lambda<Func>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(int)) { var x = Expression.Lambda<Func>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } else if (typeof(T).GetProperty(sortfield).PropertyType == typeof(DateTime)) { var x = Expression.Lambda<Func>(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); } // many more for every type return q; } 

有什么方法可以将这些ifs折叠成一个通用语句吗? 主要问题是对于Expression.Lambda<Func>这一部分Expression.Lambda<Func>我不知道如何一般地编写它。

如果将Queryable.OrderBy扩展为其定义,则不必使用Expression.Lambda的generics重载:

 public static IQueryable SortTable( IQueryable q, string sortfield, bool ascending) { var p = Expression.Parameter(typeof(T), "p"); var x = Expression.Lambda(Expression.Property(p, sortfield), p); return q.Provider.CreateQuery( Expression.Call(typeof(Queryable), ascending ? "OrderBy" : "OrderByDescending", new Type[] { q.ElementType, x.Body.Type }, q.Expression, x)); } 

这不行吗?

上述就是C#学习教程:为通用列表创建排序函数分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  public static IQueryable SortTable(IQueryable q, string sortfield, bool ascending) { var type = typeof(T).GetProperty(sortfield).PropertyType; var p = Expression.Parameter(typeof(T), "p"); var x = Expression.Lambda >(Expression.Property(p, sortfield), p); if (ascending) q = q.OrderBy(x); else q = q.OrderByDescending(x); return q; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1018387.html

(0)
上一篇 2022年1月3日
下一篇 2022年1月3日

精彩推荐