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

本文介绍了一种基于Expression Tree的LINQ排序方法,并通过具体的C#代码示例展示了如何实现自定义OrderBy和OrderByDescending功能。

最近在脑补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());
            }
        }

转载于:https://www.cnblogs.com/inobody/p/5933157.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值