Lambda表达式是一个匿名函数,它可以包含表达式和语句,并且可用于创建或表达式目录树类型。
(input parameters)=>expression
语法:左边是输入参数(如果有) 右边包含表达式或者语句块 如:x=>x*x
查询数组的案例
static void Lind_Lambda()
{
string[] strLists = new string[] { "LLT1", "LLT2", "LLT3" };
string[] strList = Array.FindAll(strLists, s => (s.IndexOf("3") >= 0));
foreach (string str in strList)
{
Console.WriteLine(str);
}
}
using System;
namespace Lambda
{
class Program
{
/*Lambda理解与应用
Lambda 就是匿名方法
*/
static void Main(string[] args)
{
Show1();
Show2();
Show3();
action1();
action2(DateTime.Now);
Console.WriteLine(func());
Console.ReadKey();
}
//声明一个委托
delegate void StudentDelegate(string name, int age);
//历史1
static void Student(string name,int age)
{
Console.WriteLine($"姓名:{name};年龄:{age}");
}
static void Show1()
{
StudentDelegate studentDelegate = new StudentDelegate(Student);
studentDelegate.Invoke("小明", 18);
}
//历史2
static void Show2()
{
StudentDelegate studentDelegate = new StudentDelegate(delegate (string name, int age)
{
Console.WriteLine($"姓名:{name};年龄:{age}");
});
studentDelegate("小红", 20);
}
//版本3(=>读成goes to)
static void Show3()
{
StudentDelegate studentDelegate = new StudentDelegate((string name, int age)=>
{
Console.WriteLine($"姓名:{name};年龄:{age}");
});
studentDelegate("匿名委托", 30);
}
//Lambda其他写法
static Action action1 = () => Console.WriteLine("无返回值,无参数");
static Action<DateTime> action2 = d => { Console.WriteLine(d + "带一个参数"); };
static Func<DateTime> func = () => DateTime.Now; //带返回值
}
}