C#(031):Lambda表达式(C# (031): lambda expression)

一、介绍

1、”Lambda表达式”是一个特殊的匿名函数,简化了匿名委托的使用,是一种高效的类似于函数式编程的表达式,Lambda简化了开发中需要编写的代码量。

2、它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型,支持带有可绑定到委托或表达式树的输入参数的内联表达式。

3、所有Lambda表达式都使用Lambda运算符=>,该运算符读作”goes
to”。Lambda运算符的左边是输入参数(如果有),右边是表达式或语句块。Lambda表达式x => x * x读作”x goes to x times
x”。

4、Lambda表达式语法:

  • 无参数:()=>expr
  • 一个参数:param=>expr
  • 多个参数:(param-list)=>expr

注意点:如果方法体内只有一句代码,可以省略代码块符号,也就是不用写{ }

二、举例:

1、 委托实例方式

    //委托  逛超市
            delegate int GuangChaoshi(int a);
            static void Main(string[] args)
            {
                GuangChaoshi gwl = JieZhang;
                Console.WriteLine(gwl(10) + "");   //打印20,委托的应用
                Console.ReadKey();
            }
            
            //结账
            public static int JieZhang(int a)
            {
                return a + 10;
            }

2、lambda表达式

    //委托  逛超市
            delegate int GuangChaoshi(int a);
            static void Main(string[] args)
            {          
               // GuangChaoshi gwl = JieZhang;
                GuangChaoshi 

gwl

     = 

p => p + 10

    ;
                Console.WriteLine(

gwl(10)

     + "");   //打印20,表达式的应用
                Console.ReadKey();
            }

3、多参数

    //委托  逛超市
            delegate int GuangChaoshi(int a,int b);
            static void Main(string[] args)
            {            
                GuangChaoshi gwl = (p,z) => z-(p + 10);
                Console.WriteLine(gwl(10,100) + "");   //打印80,z对应参数b,p对应参数a
                Console.ReadKey();
            }

三、内置委托

1、集合操作

    public class Person
        {
            public string Name { get; set; }
            public int Age  {  get;set; }    
        }
        class Program
        {
    
            public static List<Person> PersonsList()
            {
                List<Person> persons = new List<Person>();
                for (int i = 0; i < 7; i++)
                {
                    Person p = new Person() { Name = i + "儿子", Age = 8 - i, };
                    persons.Add(p);                
                }
                return persons;
            }
    
            static void Main(string[] args)
            {
                List<Person> persons = PersonsList();
                persons = persons.Where(p => p.Age > 6).ToList();       //所有Age>6的Person的集合
                Person per = persons.SingleOrDefault(p => p.Age == 1);  //Age=1的单个people类
                persons = persons.Where(p => p.Name.Contains("儿子")).ToList();   //所有Name包含儿子的Person的集合
            }
        }

2、Func委托

    static void Main(string[] args)
            {
                Func<int, int, bool> gwl = (p, j) =>
                    {
                        if (p + j == 10)
                        {
                            return true;
                        }
                        return false;
                    };
                Console.WriteLine(gwl(5,5) + "");   //打印‘True’,z对应参数b,p对应参数a
                Console.ReadKey();
            }

四、lambda表达式树动态创建方法

    static void Main(string[] args)
            {
                //i*j+w*x
                ParameterExpression a = Expression.Parameter(typeof(int),"i");   //创建一个表达式树中的参数,作为一个节点,这里是最下层的节点
                ParameterExpression b = Expression.Parameter(typeof(int),"j");
                BinaryExpression be = Expression.Multiply(a,b);    //这里i*j,生成表达式树中的一个节点,比上面节点高一级
    
                ParameterExpression c = Expression.Parameter(typeof(int), "w");
                ParameterExpression d = Expression.Parameter(typeof(int), "x");
                BinaryExpression be1 = Expression.Multiply(c, d);
    
                BinaryExpression su = Expression.Add(be,be1);   //运算两个中级节点,产生终结点
    
                Expression<Func<int, int, int, int, int>> lambda = Expression.Lambda<Func<int, int, int, int, int>>(su,a,b,c,d);
    
                Console.WriteLine(lambda + "");   //打印‘(i,j,w,x)=>((i*j)+(w*x))’,z对应参数b,p对应参数a
    
                Func<int, int, int, int, int> f= lambda.Compile();  //将表达式树描述的lambda表达式,编译为可执行代码,并生成该lambda表达式的委托;
    
                Console.WriteLine(f(1, 1, 1, 1) + "");  //打印2
                Console.ReadKey();
            }
————————

1、 Introduction

1. “Lambda expression” is a special anonymous function, which simplifies the use of anonymous delegates. It is an efficient expression similar to functional programming. Lambda simplifies the amount of code to be written in development.

2. It can contain expressions and statements, can be used to create delegate or expression tree types, and supports inline expressions with input parameters that can be bound to the delegate or expression tree.

3. All lambda expressions use the lambda operator = & gt;, This operator reads “goes.”
To “. The left side of the lambda operator is the input parameter (if any) and the right side is the expression or statement block. The lambda expression x = & gt; X * x reads as” x goes to x times ”
x”。

4. Lambda expression syntax:

  • No parameters: () = > expr
  • 一个参数:param=>expr
  • 多个参数:(param-list)=>expr

Note: if there is only one sentence of code in the method body, you can omit the code block symbol, that is, you don’t need to write {}

2、 Examples:

1. Delegate instance method

    //委托  逛超市
            delegate int GuangChaoshi(int a);
            static void Main(string[] args)
            {
                GuangChaoshi gwl = JieZhang;
                Console.WriteLine(gwl(10) + "");   //打印20,委托的应用
                Console.ReadKey();
            }
            
            //结账
            public static int JieZhang(int a)
            {
                return a + 10;
            }

2、lambda表达式

    //委托  逛超市
            delegate int GuangChaoshi(int a);
            static void Main(string[] args)
            {          
               // GuangChaoshi gwl = JieZhang;
                GuangChaoshi 

gwl

     = 

p => p + 10

    ;
                Console.WriteLine(

gwl(10)

     + "");   //打印20,表达式的应用
                Console.ReadKey();
            }

3. Multi parameter

    //委托  逛超市
            delegate int GuangChaoshi(int a,int b);
            static void Main(string[] args)
            {            
                GuangChaoshi gwl = (p,z) => z-(p + 10);
                Console.WriteLine(gwl(10,100) + "");   //打印80,z对应参数b,p对应参数a
                Console.ReadKey();
            }

3、 Built in delegate

1. Collection operation

    public class Person
        {
            public string Name { get; set; }
            public int Age  {  get;set; }    
        }
        class Program
        {
    
            public static List<Person> PersonsList()
            {
                List<Person> persons = new List<Person>();
                for (int i = 0; i < 7; i++)
                {
                    Person p = new Person() { Name = i + "儿子", Age = 8 - i, };
                    persons.Add(p);                
                }
                return persons;
            }
    
            static void Main(string[] args)
            {
                List<Person> persons = PersonsList();
                persons = persons.Where(p => p.Age > 6).ToList();       //所有Age>6的Person的集合
                Person per = persons.SingleOrDefault(p => p.Age == 1);  //Age=1的单个people类
                persons = persons.Where(p => p.Name.Contains("儿子")).ToList();   //所有Name包含儿子的Person的集合
            }
        }

2、Func委托

    static void Main(string[] args)
            {
                Func<int, int, bool> gwl = (p, j) =>
                    {
                        if (p + j == 10)
                        {
                            return true;
                        }
                        return false;
                    };
                Console.WriteLine(gwl(5,5) + "");   //打印‘True’,z对应参数b,p对应参数a
                Console.ReadKey();
            }

4、 Dynamic creation method of lambda expression tree

    static void Main(string[] args)
            {
                //i*j+w*x
                ParameterExpression a = Expression.Parameter(typeof(int),"i");   //创建一个表达式树中的参数,作为一个节点,这里是最下层的节点
                ParameterExpression b = Expression.Parameter(typeof(int),"j");
                BinaryExpression be = Expression.Multiply(a,b);    //这里i*j,生成表达式树中的一个节点,比上面节点高一级
    
                ParameterExpression c = Expression.Parameter(typeof(int), "w");
                ParameterExpression d = Expression.Parameter(typeof(int), "x");
                BinaryExpression be1 = Expression.Multiply(c, d);
    
                BinaryExpression su = Expression.Add(be,be1);   //运算两个中级节点,产生终结点
    
                Expression<Func<int, int, int, int, int>> lambda = Expression.Lambda<Func<int, int, int, int, int>>(su,a,b,c,d);
    
                Console.WriteLine(lambda + "");   //打印‘(i,j,w,x)=>((i*j)+(w*x))’,z对应参数b,p对应参数a
    
                Func<int, int, int, int, int> f= lambda.Compile();  //将表达式树描述的lambda表达式,编译为可执行代码,并生成该lambda表达式的委托;
    
                Console.WriteLine(f(1, 1, 1, 1) + "");  //打印2
                Console.ReadKey();
            }