码迷,mamicode.com
首页 > 编程语言 > 详细

通过Expression 动态实现IEnumerable<T> CustomOrderBy

时间:2016-10-06 00:06:16      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

最近在脑补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

标签:

原文地址:http://www.cnblogs.com/inobody/p/5933157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!