首页 > 代码库 > part01.03 委托与 Lambda 表达式(三):Lambda 表达式

part01.03 委托与 Lambda 表达式(三):Lambda 表达式

“Lambda 表达式”是一个匿名函数,它可以包含表达式和语句,用于创建委托或表达式树类型

A. 用Lambda表达式代替匿名方法,复杂冗长的形式

格式:( 显式类型参数列表 )=>{ 语句 }

样例:

       //  带返回值的委托
            Func<int, double, double> a = (m, n) => { return m * n; };
            Console.WriteLine(a);
            Console.WriteLine(a(10, 25.2));

            //  不带返回值的委托
            Action<int> b = x => { Console.WriteLine(x); };
            b(100);

B. 用简单表达式作为主体:用一个表达式表示一个整体,该表达式的值就是Lambda的结果

格式:( 显式的参数列表 )=>表达式

样例:

  ( string iReason, DateTime iDate ) => iDate == DateTime.Parse("2010-10-10")

  ( Person xiaozhang )=>xiaozhang.Height

C. 隐式类型的参数列表

格式:( 隐式参数列表 )=>表达式

样例:

  ( iReason, iDate ) => iDate == DateTime.Parse("2010-10-10")

  ( xiaozhang )=>xiaozhang.Height

D. 单一参数的快捷语法

格式:参数名 => 表达式

样例:xiaozhang=>xiaozhang.Height

 

技术分享

在集合查询中应用 Lambda 表达式

 技术分享

Lambda 表达式应用注意事项简要说明

技术分享

技术分享

技术分享

Lambda 表达式和匿名方法的比较

总体上说,匿名方法可以看做是 Lambda 表达式的功能子集,但是两者存在以下区别:

1. Lambda 表达式的参数允许不指明参数类型,而匿名方法的参数必须明确指明参数类型

2. Lambda 表达式的方法体允许由单一表达式或者多条语句组成,而匿名方法不允许单一表达式形式

Lambda 表达式树

技术分享

表达式树的构建使用例子

详细请看相关代码:

技术分享
 1 class Program
 2     {
 3         /// <summary>
 4         /// 依据 IQueryable 集合,数据源构造一个查询,然后执行该查询。 代码将生成一个表达式树来表示以下查询:
 5         /// companies.Where(company => (company.ToLower() == "coho winery" || company.Length > 16)).OrderBy(company => company)
 6         /// </summary>
 7         /// <param name="args"></param>
 8         static void Main(string[] args)
 9         {
10             string[] companies = { "Consolidated Messenger", "Alpine Ski House", "Southridge Video", "City Power & Light",
11                    "Coho Winery", "Wide World Importers", "Graphic Design Institute", "Adventure Works",
12                    "Humongous Insurance", "Woodgrove Bank", "Margie‘s Travel", "Northwind Traders",
13                    "Blue Yonder Airlines", "Trey Research", "The Phone Company",
14                    "Wingtip Toys", "Lucerne Publishing", "Fourth Coffee" };
15 
16             // 转型为 IQueryable<String>
17             IQueryable<String> queryableData = http://www.mamicode.com/companies.AsQueryable<string>();
18 
19             // 组合表达式树作为参数推断的依据  
20             ParameterExpression pe = Expression.Parameter(typeof(string), "company");
21 
22             #region 构建推断条件:Where(company => (company.ToLower() == "coho winery" || company.Length > 16))
23             // 创建表达式树代表条件 ‘company.ToLower() == "coho winery"‘.  
24             Expression left = Expression.Call(pe, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
25             Expression right = Expression.Constant("coho winery");
26             Expression e1 = Expression.Equal(left, right);
27 
28             // 创建表达式树代表条件 ‘company.Length > 16‘.  
29             left = Expression.Property(pe, typeof(string).GetProperty("Length"));
30             right = Expression.Constant(16, typeof(int));
31             Expression e2 = Expression.GreaterThan(left, right);
32 
33             // 组合表达式树代表: ‘(company.ToLower() == "coho winery" || company.Length > 16)‘.  
34             Expression predicateBody = Expression.OrElse(e1, e2);
35 
36             // 创建表达式树代表条件 ‘queryableData.Where(company => (company.ToLower() == "coho winery" || company.Length > 16))‘  
37             MethodCallExpression whereCallExpression = Expression.Call(
38                 typeof(Queryable),
39                 "Where",
40                 new Type[] { queryableData.ElementType },
41                 queryableData.Expression,
42                 Expression.Lambda<Func<string, bool>>(predicateBody, new ParameterExpression[] { pe }));
43             #endregion
44 
45             #region 构建排序条件:OrderBy(company => company)
46             // 创建表达式树代表条件 ‘whereCallExpression.OrderBy(company => company)‘  
47             MethodCallExpression orderByCallExpression = Expression.Call(
48                 typeof(Queryable),
49                 "OrderBy",
50                 new Type[] { queryableData.ElementType, queryableData.ElementType },
51                 whereCallExpression,
52                 Expression.Lambda<Func<string, string>>(pe, new ParameterExpression[] { pe })); 
53             #endregion
54 
55             // 执行处理结果  
56             IQueryable<string> results = queryableData.Provider.CreateQuery<string>(orderByCallExpression);
57 
58             // 枚举结果  
59             foreach (string company in results)
60                 Console.WriteLine(company);
61 
62             Console.ReadKey();
63         }
64     }
View Code

常见的使用委托和 Lambda 表达式的场景与实现

技术分享
 1 public class Person
 2     {
 3         public Guid ID { get; set; }
 4         public string Name { get; set; }
 5         public string Description { get; set; }
 6         public string SortCode { get; set; }
 7         public string FirstName { get; set; }
 8         public string LastName { get; set; }
 9         public string Mobile { get; set; }
10         public string Email { get; set; }
11 
12         public virtual Department Department { get; set; }
13 
14         public Person()
15         {
16             this.ID = Guid.NewGuid();
17             this.SortCode = DateTime.Now.ToString("yyyyMMddhhmmssfff");
18         }
19     }
20 
21  public class Department
22     {
23         public Guid ID { get; set; }
24         public string Name { get; set; }
25         public string Description { get; set; }
26         public string SortCode { get; set; }
27 
28         public virtual Department ParentDepartment { get; set; }
29 
30         public Department()
31         {
32             this.ID = Guid.NewGuid();
33         }
34     }
基本业务代码
技术分享
  1  public static class PersonRepository
  2     {
  3         public static List<Department> Departments { get; set; }
  4         public static List<Person> People { get; set; }
  5 
  6         static PersonRepository()
  7         {
  8             _Initializer();
  9         }
 10 
 11         public static void _Initializer()
 12         {
 13 
 14             #region 初始化部门数据
 15 
 16             Departments = new List<Department>();
 17             var dept01 = new Department
 18             {
 19                 Name = "南宁市信息技术有限责任公司",
 20                 Description = "",
 21                 SortCode = "01"
 22             };
 23             dept01.ParentDepartment = dept01;
 24             Departments.Add(dept01);
 25 
 26             var dept0101 = new Department
 27             {
 28                 Name = "综合管理部",
 29                 Description = "负责公司办公、人事、财务日常管理工作。",
 30                 SortCode = "0101",
 31                 ParentDepartment = dept01
 32             };
 33             Departments.Add(dept0101);
 34 
 35             var dept0102 = new Department
 36             {
 37                 Name = "营销部",
 38                 Description = "负责公司商业项目售前与售后支持工作。",
 39                 SortCode = "0102",
 40                 ParentDepartment = dept01
 41             };
 42             Departments.Add(dept0102);
 43 
 44             var dept0103 = new Department
 45             {
 46                 Name = "技术部",
 47                 Description = "负责公司商业项目具体实施开发工作",
 48                 SortCode = "0102",
 49                 ParentDepartment = dept01
 50             };
 51             Departments.Add(dept0103);
 52 
 53             #endregion
 54 
 55             #region 初始化人员数据
 56 
 57             People = new List<Person>
 58             {
 59                 new Person { Name = "张小祎", Description = "北京", Department = dept01, Email = "zhangxw@hotmail.com" },
 60                 new Person { Name = "李珊柳", Description = "北京", Department = dept01, Email = "lishsh@hotmail.com" },
 61                 new Person { Name = "李华语", Description = "河北", Department=dept0101, Email = "lihy@hotmail.com" },
 62                 new Person { Name = "黄慧琳", Description = "河北", Department=dept0101,Email = "huanghl@hotmail.com" },
 63                 new Person { Name = "潘加伟", Description = "河北", Department=dept0101, Email = "panjw@hotmail.com" },
 64                 new Person { Name = "秦小梨", Description = "河北", Department=dept0101, Email = "qinxl@hotmail.com" },
 65                 new Person { Name = "覃晓琳", Description = "河北", Department=dept0101,Email = "qinxlin@hotmail.com" },
 66                 new Person { Name = "韦长英", Description = "广西", Department=dept0101, Email = "weichy@hotmail.com" },
 67                 new Person { Name = "韦大东", Description = "广西", Department=dept0102, Email = "1918625568@qq.com" },
 68                 new Person { Name = "韦家文", Description = "广西", Department=dept0101,  Email = "2918625578@qq.com" },
 69                 new Person { Name = "黎文新", Description = "广西", Department=dept0101,Email = "1918625592@qq.com" },
 70                 new Person { Name = "黎子流", Description = "广东", Department=dept0102, Email = "1918625593@qq.com" },
 71                 new Person { Name = "余卫东", Description = "广东", Department=dept0102,  Email = "1918625591@qq.com" },
 72                 new Person { Name = "何家宝", Description = "广东", Department=dept0102, Email = "1918625566@qq.com" },
 73                 new Person { Name = "何欣俊", Description = "广东", Department=dept0102,Email = "1918625555@qq.com" },
 74                 new Person { Name = "余华亮", Description = "广东", Department=dept0102, Email = "1918625533@qq.com" },
 75                 new Person { Name = "汤富贵", Description = "广东", Department=dept0102,Email = "1918625532@qq.com" },
 76                 new Person { Name = "唐富贵", Description = "广东", Department=dept0102, Email = "1918625536@qq.com" },
 77                 new Person { Name = "唐蔚佳", Description = "广东", Department=dept0103,  Email = "tangwj@hotmail.com" },
 78                 new Person { Name = "谢显才", Description = "广东", Department=dept0103,Email = "xiexc@hotmail.com" },
 79                 new Person { Name = "解晓东", Description = "广东", Department=dept0103,  Email = "xiexd@hotmail.com" },
 80                 new Person { Name = "谢家麟", Description = "广东", Department=dept0103,Email = "xiejl@hotmail.com" },
 81                 new Person { Name = "谢子怡", Description = "广东", Department=dept0103, Email = "xieziy@hotmail.com" },
 82                 new Person { Name = "张建光", Description = "广东", Department=dept0103, Email = "zhangjg@163.com" },
 83                 new Person { Name = "李振书", Description = "广东", Department=dept0103,  Email = "lizhsh@163.com" },
 84                 new Person { Name = "陈丰州", Description = "广东", Department=dept0103, Email = "chenfzh@163.com" },
 85                 new Person { Name = "陈卫东", Description = "广东", Department=dept0103, Email = "chenwd@163.com" },
 86                 new Person { Name = "陈峰受", Description = "广东", Department=dept0103, Email = "chenfsh@163.com" },
 87                 new Person { Name = "陈金健", Description = "广东", Department=dept0103,Email = "chenjj@163.com" },
 88                 new Person { Name = "韦海波", Description = "广东", Department=dept0103, Email = "weihb@163.com" },
 89                 new Person { Name = "祁宣明", Description = "广东", Department=dept0103, Email = "qixm@163.com" },
 90                 new Person { Name = "戚计生", Description = "上海", Department=dept01,  Email = "qijsh@163.com" },
 91                 new Person { Name = "石智生", Description = "广西", Department=dept0101,Email = "shizhsh@163.com" },
 92                 new Person { Name = "苏晓琳", Description = "广西", Department=dept0101,  Email = "suxl@hotmail.com" },
 93                 new Person { Name = "苏振彪", Description = "广西", Department=dept0101, Email = "suzhb@sina.com.cn" },
 94                 new Person { Name = "谭家伟", Description = "广西", Department=dept0101, Email = "tanjw@sina.com.cn" },
 95                 new Person { Name = "谭俊杰", Description = "广西", Department=dept01,Email = "tanjj@sina.com.cn" },
 96                 new Person { Name = "王定祠", Description = "广西", Department=dept01,  Email = "wangdc@sina.com.cn" },
 97                 new Person { Name = "王金生", Description = "广西", Department=dept01,  Email = "wangjsh@sina.com.cn" },
 98                 new Person { Name = "王宝军", Description = "广西", Department=dept0103,  Email = "wangbj@sina.com.cn" },
 99                 new Person { Name = "吴克标", Description = "广西", Department=dept0103, Email = "wukb@hotmail.com" },
100                 new Person { Name = "吴斌", Description = "江西", Department=dept0103,  Email = "wubing@hotmail.com" },
101                 new Person { Name = "游毅峰", Description = "湖南", Department=dept0103,  Email = "youyf@hotmail.com" },
102                 new Person { Name = "柳君华", Description = "湖南", Department=dept0103,  Email = "liujh@hotmail.com" },
103                 new Person { Name = "刘小薇", Description = "湖南", Department=dept0103,  Email = "liuxw@hotmail.com" },
104                 new Person { Name = "陈东风", Description = "湖南", Department=dept0103,  Email = "chendf@hotmail.com" },
105                 new Person { Name = "欧阳海", Description = "湖南", Department=dept0103,  Email = "ouyangpj@hotmail.com" },
106                 new Person { Name = "柳三变", Description = "湖南", Department=dept0103,  Email = "liusb@hotmail.com" },
107                 new Person { Name = "郭骁", Description = "北京", Department=dept0103,Email = "zhanguoxiao@hotmail.com" },
108                 new Person { Name = "郭家铭", Description = "香港", Department=dept0103,  Email = "guojm@hotmail.com" },
109                 new Person { Name = "陈兆年", Description = "四川", Department=dept0103,  Email = "chanzhn@hotmail.com" },
110                 new Person { Name = "农卫红", Description = "四川", Department=dept0103,  Email = "nongwh@hotmail.com" },
111                 new Person { Name = "农志升", Description = "四川", Department=dept0103,  Email = "nongzhsh@hotmail.com" },
112                 new Person { Name = "农小琳", Description = "四川", Department=dept0103, Email = "nongxl@hotmail.com" },
113                 new Person { Name = "徐荣国", Description = "四川", Department=dept0103,  Email = "xurg@live.com" },
114                 new Person { Name = "聂小威", Description = "四川", Department=dept0103,  Email = "niexw@live.com" },
115                 new Person { Name = "邱福林", Description = "四川", Department=dept0103,  Email = "qiufl@live.com" },
116                 new Person { Name = "范思坦", Description = "四川", Department=dept0103,  Email = "fanst@live.com" },
117                 new Person { Name = "邓唯佳", Description = "四川", Department=dept0103, Email = "dengwj@hotmail.com" },
118                 new Person { Name = "马晓东", Description = "云南", Department=dept0103,  Email = "maxd@hotmail.com" },
119                 new Person { Name = "魏明翠", Description = "云南", Department=dept0103,  Email = "weimc@hotmail.com" },
120                 new Person { Name = "尹相杰", Description = "贵州", Department=dept0103,  Email = "yinxj@hotmail.com" },
121                 new Person { Name = "张小祎", Description = "贵州", Department=dept0103,  Email = "zhangxw@163.com" }
122             };
123 
124             #endregion
125         }
126     }
初始化数据代码

1.基本查询操作符-获取数据:

Select() 方法:

public static IEnumerable<TResult> Select<TSource, TResult> (this IEnumerable<TSource> source, Func<TSource, TResult> selector )

说明:

  。Select 方法本身是一个泛型扩展方法

  。它作用于 IEnumerable<TSource> 类型

  。它只接受一个 Func<TSoursce,TResult> 类型参数

  。Func<TSource,TResult>是一个泛型委托,位于 System 名字空间下,System.Core.dll 中

  。在这里 selector 是一个提取器

 技术分享

2.基本查询操作符-过滤数据
Where()方法:
public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate )
说明:
  。Where方法也是一个泛型扩展方法
  。它和 Select() 一样作用于IEnumerable<TSource>类型
  。它只接受一个 Func<TSource, bool> 泛型委托参数
  。在这里 predicate 是一个判断条件

 技术分享

3.基本查询操作符-排序数据:
OrderBy()方法:
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector )
说明
  。OrderBy方法也是一个泛型扩展方法
  。它和 Select() 一样作用于IEnumerable<TSource>类型
  。它只接受一个 Func<TSource, TKey > 类型参数
  。在这里 keySelector 指定要排序的字段
  。如果想降序排列可以使用OrderByDescending方法

技术分享

4.基本查询操作符-分组数据:
GroupBy()方法
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector )
说明
  。GroupBy方法和OrderBy方法非常类似,它也是一个泛型扩展方法
  。它和 OrderBy() 一样作用于IEnumerable<TSource>类型
  。它只接受一个 Func<TSource, TKey > 类型参数
  。在这里 keySelector 指定要分组的字段

 技术分享

 

 

 

参考网址:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/statements-expressions-operators/anonymous-functions

part01.03 委托与 Lambda 表达式(三):Lambda 表达式