Lambda表达式只是用更简单的方式来写匿名方法,彻底简化了对.NET委托类型的使用。
现在,如果我们要使用泛型 List<> 的 FindAll() 方法,当你从一个集合去提取子集时,可以使用该方法。
// 该方法唯一的参数是一个System.Predicate<T>类型的泛型委托
public List<T> FindAll(Predicate<T> match); // 该委托指向任意以类型参数作为唯一输入参数并返回bool的方法
public delegate bool Predicate<in T>(T obj);
在调用 FindAll() 时,List<T>中每一项都将传入Predicate<T> 对象所指向的方法。方法在实现时将执行一些计算,来判断传入的数据是否符合标准,并返回 true / false,如果返回 true ,该项被添加到表示自己的List<T>集合中。
现在,我们需要从一个List<int>集合中找到所有偶数,该如何实现呢?
1.传统方法
public class MyDelegateSyntax
{public static void Show()
{
Console.WriteLine("fun with lambdas"); List<int> list = new List<int> { , , , , , }; Predicate<int> callback = new Predicate<int>(IsEvenNumber); // 传统方法
List<int> evenList = list.FindAll(callback); Console.WriteLine(); foreach (int item in evenList)
{
Console.WriteLine(item);
}
} private static bool IsEvenNumber(int obj) => obj % == ;
}
2.匿名方法
public class MyDelegateSyntax
{
public static void Show()
{
Console.WriteLine("fun with lambdas"); List<int> list = new List<int> { , , , , , }; // 匿名方法
List<int> evenList = list.FindAll(delegate (int i)
{
return i % == ;
}); Console.WriteLine(); foreach (int item in evenList)
{
Console.WriteLine(item);
}
}
}
3.Lambda表达式
public class MyDelegateSyntax
{
public static void Show()
{
Console.WriteLine("fun with lambdas"); List<int> list = new List<int> { , , , , , }; // Lambda表达式
// 隐式,编辑器会更具上下文表达式推断i的类型
List<int> evenList = list.FindAll(i => i % == ); // 显式
// 描述:我的参数列表(一个整形i)将会被表达式(i%2)==0处理
List<int> evenList1 = list.FindAll((int i) => i % == ); // 我的参数列表(一个整形i)将会被表达式(i%2)==0处理 Console.WriteLine(); foreach (int item in evenList)
{
Console.WriteLine(item);
}
}
}
4.使用多个语句处理参数(“{}”)
public class MyDelegateSyntax
{
public static void Show()
{
Console.WriteLine("fun with lambdas"); List<int> list = new List<int> { , , , , , }; // 多个处理语句 语句块 {}
List<int> evenList = list.FindAll(i =>
{
Console.WriteLine(i);
return i % == ;
}); Console.WriteLine(); foreach (int item in evenList)
{
Console.WriteLine(item);
}
}
}
5.含有多个(或零个)参数的Lambda表达式
public class MyDelegateSyntax
{
public delegate string VerySimpleDelegate(); public delegate void MathMessage(string msg, int result); public static void Show()
{
Console.WriteLine("fun with lambdas");
// 多个参数的Lambda
MathMessage mm = new MathMessage((msg, result) => Console.WriteLine($"msg:{msg} result:{result}"));
mm("adding has cmpleted", + ); // 0个参数Lambda
VerySimpleDelegate d = new VerySimpleDelegate(() => "enjoy you string");
Console.WriteLine(d.Invoke());
}
}
学无止境,望各位看官多多指教。