[
lambda本质上是一个委托,他是匿名委托,有的资料叫匿名函数,其实lambda本身是从函数式编程语言中发展而来,函数式编程语言里函数是第一等元素,函数的参数,函数的返回值都是函数,程序没有变量,函数嵌套函数。而且函数式编程语言一直存在于象牙塔中,所以在工业界并没有得到通用,不过近年来工业界比较喜欢“复古”风格,所以函数式编程语言也慢慢的走上了历史的舞台。我们现在的编程叫命令式编程,函数式编程能很好的解决命令式编程不能解决的问题。
学习lambda是很有用的,特别是结合表达树,当然了如果组装表达树给人的感觉就是一个简单的查询都会被写成狂长的一堆语句,如果你公司是按照代码行计算工资的倒是值得祝贺,就目前看也没办法,只能期待Linq在未来能更好的发展,老实说要能很好的使用Linq必须要解决动态查询(在以前就是拼装SQL语句),要能深刻的理解动态查询就要学好lambda和表达树,关于微软提供的Dynamic.cs早期学习的时候可以少用,等搞清表达树后使用也不迟。关于表达树有机会在和大家聊聊.
]
转自:url[http://www.wfseo.cn/blog/post/51.html]
看个例子:
int[] arr = new int[] {1,2,3};
我们用这个数组刷选排序:
一般情况下我们这样写:
var q = arr.Where(p => p >1 ).Select(p => p).OrderBy(n => n);
写法1:
private static bool myWhere(int i) { return i>5; } Func<int, bool> f2 = myWhere; var q = arr.Where(f2).Select(p => p).OrderBy(n => n);
写法2:
var q1 = arr.Where(delegate(int p) { return p > 5; }).Select(p => p).OrderBy(n => n);
以下是源码:
------------------------------------------------------------------------------------------------------------------------------
// // Summary: // Filters a sequence of values based on a predicate. Each element's index is // used in the logic of the predicate function. // // Parameters: // source: // An System.Collections.Generic.IEnumerable<T> to filter. // // predicate: // A function to test each source element for a condition; the second parameter // of the function represents the index of the source element. // // Type parameters: // TSource: // The type of the elements of source. // // Returns: // An System.Collections.Generic.IEnumerable<T> that contains elements from // the input sequence that satisfy the condition. // // Exceptions: // System.ArgumentNullException: // source or predicate is null. public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
----------------------------------------------------------------------------------------------------------------------------------
namespace System { // Summary: // Encapsulates a method that has one parameter and returns a value of the type // specified by the TResult parameter. // // Parameters: // arg: // The parameter of the method that this delegate encapsulates. // // Type parameters: // T: // The type of the parameter of the method that this delegate encapsulates. // // TResult: // The type of the return value of the method that this delegate encapsulates. // // Returns: // The return value of the method that this delegate encapsulates. public delegate TResult Func<T, TResult>(T arg); } Where(),传入一个int返回bool;