首页 > 代码库 > 通过Expression 动态实现IEnumerable<T> CustomOrderBy
通过Expression 动态实现IEnumerable<T> CustomOrderBy
最近在脑补Expression Tree 系列 http://www.cnblogs.com/Ninputer/archive/2009/08/28/expression_tree1.html
然后发现 http://www.codeproject.com/Articles/235860/Expression-Tree-Basics 写得相当不错。
所以就稍微改动,实现了如下代码
public static IEnumerable OrderBy(this IEnumerable source, string propertyName, bool desc = false) { if (source == null) throw new ArgumentNullException("source"); if (string.IsNullOrEmpty(propertyName)) return source; var item = Expression.Parameter(typeof(T), "item"); var prop = Expression.Property(item, propertyName); var keySelector = Expression.Lambda(prop, item); var param = Expression.Parameter(typeof(IEnumerable), "source"); var orderBy = Expression.Call(typeof(Enumerable), (desc ? "OrderByDescending" : "OrderBy"), new[] { typeof(T), prop.Type }, param, keySelector); var sorter = Expression.Lambda, IEnumerable>>(orderBy, param); return sorter.Compile()(source); }
使用方法:
public class Student { public string Name { get; set; } public int Age { get; set; } public Student(string name, int age) { this.Name = name; this.Age = age; } public override string ToString() { return string.Format("Name:{0}\t Age:{1}", this.Name, this.Age); } } static void Main(string[] args) { List list = new List { new Student("张三",13), new Student("李四",15), new Student("王五",14) }; var sortList = list.OrderBy("Age"); foreach (var item in sortList) { Console.WriteLine(item.ToString()); } Console.WriteLine("\nDesc:\n"); var sortList2 = list.OrderBy("Age", true); foreach (var item in sortList2) { Console.WriteLine(item.ToString()); } }
通过Expression 动态实现IEnumerable<T> CustomOrderBy
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。