lambda表达式和表达式树

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();
        }
    }
}
原文地址:https://www.cnblogs.com/FangZhaohu/p/5069445.html