Lambda表达式入门
1. 什么是Lambda表达式?
2. 在什么时候用到它,它有什么优点?
3. Lambda表达式的真面目是什么样的?
什么是Lambda表达式
C# 2.0 (which shipped with VS 2005) introduced the concept of anonymous methods, which allow code blocks to be written "in-line" where delegate values are expected.
Lambda Expressions provide a more concise, functional syntax for writing anonymous methods. They end up being super useful when writing LINQ query expressions - since they provide a very compact and type-safe way to write functions that can be passed as arguments for subsequent evaluation.
这是牛人的解释,翻译过来的意思是:
C#2.0说明了匿名函数的概念,匿名函数就是允许在使用委托的地方通过"in-line"操作来写代码(其实就是delegate(int i) {... 这里...})。Lambda表达式提供了一个更简单更语法化的方式来书写匿名函数。它们在LINQ查询表达式中很有用-因为它们提供了更精简并且类型安全的方法来书写函数,就像传递参数一样用于 subsequent evaluation(不会译了^_^)。
在什么时候用到它,它有什么优点
在什么时候用Lambda表达式呢?其实在LINQ查询语句出来后,用的情况就很少了,不过呢?如果你还工作在.net2.0 或额.net3.0 framework下还是可以用的,你可以对集合操作使用Lambda表达式。但是你不能对简单函数使用Lambda表达式(什么是简单函数呢?下面在说)。至于Lambda表达式的优点也就是简化了coding和增加了类型安全。
Lambda表达式的真面目是什么样的
这个问题我要用3个例子来渐进的说明。
(1)使用Lambda表达式在程序中:
static void Main(string[] args)2
{3
List<int> myList = new List<int> { 1,2,3,4,5 };4

5
// 1.Lambda experssion6
int val1 = myList.Find(i=> i == 4);7
Console.WriteLine(val1);8

9
Console.ReadKey();10
}(2)在近一步
static void Main(string[] args)2
{3
List<int> myList = new List<int> { 1,2,3,4,5 };4

5
// 2. Lambda experssion using delegate6
int val2 = myList.Find(delegate(int i) { return (i==4); });7
Console.WriteLine(val2);8

9
Console.ReadKey();10
}(3)最终的面貌
private static Predicate<int> _tmpList;2

3
static void Main(string[] args)4
{5
List<int> myList = new List<int> { 1,2,3,4,5 };6

7
// 3. Lambda experssion implement 8
if (_tmpList == null)9
{10
_tmpList = new Predicate<int>(Compare);11
}12
int val3 = myList.Find(_tmpList);13
Console.WriteLine(val3);14

15
Console.ReadKey();16
}17

18
private static bool Compare(int i)19
{20
return (i == 4);21
}


List
浙公网安备 33010602011771号