zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    Android基本功:Socket
    Javascript模板及其中的数据逻辑分离思想
    MFC,QT与WinForm,WPF简介
    GPIB、USB、PCI、PCI Express和以太网/LAN/LXI
    Office批量授权(VL)版本和激活方法
    Labview 错误1400-打包库封装类时将对类重命名导致
    console.log()
    a标签中href=""的几种用法
    正斜杠"/"与反斜杠""
    提问的艺术
  • 原文地址:https://www.cnblogs.com/FangZhaohu/p/5069445.html
Copyright © 2011-2022 走看看