最近在脑补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()); } }
时间: 2024-10-29 19:10:44