拉姆达表达式/Lambda表达式/lambda expression 使用整理
一、Lamabda表达式定义
Lambda 表达式(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。 Lambda表达式可以表示闭包,最早出现C#3.0,随着时间推移新版本JavaScript、Java8,Pathton等语言也都开始支持。
更多匿名函数介绍:
二、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); });
更多: