拉姆达表达式/Lambda表达式/lambda expression 使用整理

一、Lamabda表达式定义

Lambda 表达式(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。
Lambda表达式可以表示闭包,最早出现C#3.0,随着时间推移新版本JavaScript、Java8,Pathton等语言也都开始支持。

更多匿名函数介绍:https://blog.csdn.net/u011127019/article/details/113714566

 

二、Lamabda表达式语法

C#、JavaScript的语法一样: 用=> 符号声明

参数列表 => 语句或语句块

Java/C++的语法一样: 用-> 符号声明

参数列表 -> 语句或语句块

Pathon中:用:符号声明

 

三、C# 中Lamabda使用场景

1.拉姆达表达式 和 委托

public delegate void NoticeAll(string name);
static void LambdaTest()
{
    //拉姆达表达式 和  委托
    NoticeAll notice1 = (name1) =>
    {
        Console.WriteLine($"济南通知到了,{name1}");
    };
    notice1 += (name2) =>
    {
        Console.WriteLine($"聊城通知到了【{name2}】");
    };
    //触发委托的多播链
    notice1("张三");


    //拉姆达表达式回调
    GetSum(10, 20, res =>
    {
        Console.WriteLine("计算结果:" + res);
    });
}
static void GetSum(int num1, int num2, Action<int> onSuccess)
{
    int result = num1 + num2;
    if (onSuccess != null)
        onSuccess(result);
}

2.拉姆达表达式 和 Linq

        static void LambdaTest2()
        {
            //拉姆达表达式 和 Linq
            int[] nums = new int[] { 10, 1, 3, 5, -2 };
            int max = nums.Max();


            List<Student> list = new List<Student>() {
                new Student(){ID=1,Name="张三",Score=100 },
                new Student(){ID=2,Name="李四",Score=80 },
                new Student(){ID=3,Name="王五",Score=60 },
                new Student(){ID=4,Name="赵六",Score=120 },
            };
            // 找id=1 的学生
            Student studen1 = list.Where(q => q.Score == 1).FirstOrDefault();

            //找最高分
            decimal maxScore = list.Max(q => q.Score);

        }
        public class Student
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public decimal Score { get; set; }
        }

3.拉姆达表达式树 Expression

//定义表达式
Expression<Func<Student, bool>> lambda1 = q => q.Score > 60;
Expression<Func<Student, bool>> lambda2 = q => q.ID > 1;
//合并表达式
BinaryExpression temp = Expression.And(lambda1, lambda2);
Expression<Func<Student, bool>> lambda3 = Expression.Lambda<Func<Student, bool>>(temp);
//执行表达式
Student student2 = list.Where(lambda3.Compile()).FirstOrDefault();

四、JavaScript 表达式使用

nodejs中支持,新版本的浏览器中也都支持了。

function getSum(num1,num2,onSuccess){
    var result=num1+num2;
    onSuccess(result);
}
//回调函数,匿名
getSum(20,30,res=>{
    console.info('计算结果:'+res);
});

 

更多:

C# 委托、事件、回调 讲解

C# 匿名函数_C# 匿名函数使用整理

C# 匿名对象_C#匿名类型_C# 匿名对象使用整理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值