码迷,mamicode.com
首页 > 其他好文 > 详细

lambda表达式和表达式树

时间:2015-12-23 12:36:12      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

namespace LambdaDemo
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    internal static class Program
    {
        static void Main(string[] args)
        {
            List<Person> persons = GetPersonList();
            persons = persons.Where(p => p.Age > 6).ToList();
            Person personP = persons.SingleOrDefault(p => p.Age == 2);
            List<Person> personsC = persons.Where(p => p.Name.Contains("儿子")).ToList();

            ExpressionMethod();
        }


        private static List<Person> GetPersonList()
        {
            List<Person> plist = new List<Person>();
            for (int i = 0; i < 7; i++)
            {
                plist.Add(new Person {Name = "儿子", Age = 8 - i});
            }
            return plist;
        }

        // 表达式树
        private static void ExpressionMethod()
        {
            //计算 a*b+c*d的值
            ParameterExpression a = Expression.Parameter(typeof (int), "a");
            ParameterExpression b = Expression.Parameter(typeof (int), "b");
            BinaryExpression ab = Expression.Multiply(a, b);

            ParameterExpression c = Expression.Parameter(typeof (int), "c");
            ParameterExpression d = Expression.Parameter(typeof (int), "d");
            BinaryExpression cd = Expression.Multiply(c, d);

            BinaryExpression abcd = Expression.Add(ab, cd);
            Expression<Func<int, int, int, int, int>> lam = Expression.Lambda<Func<int, int, int, int, int>>(abcd, a, b,
                c, d);
            Console.WriteLine(lam + "");
            Func<int, int, int, int, int> f = lam.Compile();
            Console.WriteLine(f(2, 1, 5, 1) + "");
            Console.ReadKey();
        }
    }
}

 

lambda表达式和表达式树

标签:

原文地址:http://www.cnblogs.com/FangZhaohu/p/5069445.html

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