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 = 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     }

常见的使用委托和 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 = "[email protected]" },
 60                 new Person { Name = "李珊柳", Description = "北京", Department = dept01, Email = "[email protected]" },
 61                 new Person { Name = "李华语", Description = "河北", Department=dept0101, Email = "[email protected]" },
 62                 new Person { Name = "黄慧琳", Description = "河北", Department=dept0101,Email = "[email protected]" },
 63                 new Person { Name = "潘加伟", Description = "河北", Department=dept0101, Email = "[email protected]" },
 64                 new Person { Name = "秦小梨", Description = "河北", Department=dept0101, Email = "[email protected]" },
 65                 new Person { Name = "覃晓琳", Description = "河北", Department=dept0101,Email = "[email protected]" },
 66                 new Person { Name = "韦长英", Description = "广西", Department=dept0101, Email = "[email protected]" },
 67                 new Person { Name = "韦大东", Description = "广西", Department=dept0102, Email = "[email protected]" },
 68                 new Person { Name = "韦家文", Description = "广西", Department=dept0101,  Email = "[email protected]" },
 69                 new Person { Name = "黎文新", Description = "广西", Department=dept0101,Email = "[email protected]" },
 70                 new Person { Name = "黎子流", Description = "广东", Department=dept0102, Email = "[email protected]" },
 71                 new Person { Name = "余卫东", Description = "广东", Department=dept0102,  Email = "[email protected]" },
 72                 new Person { Name = "何家宝", Description = "广东", Department=dept0102, Email = "[email protected]" },
 73                 new Person { Name = "何欣俊", Description = "广东", Department=dept0102,Email = "[email protected]" },
 74                 new Person { Name = "余华亮", Description = "广东", Department=dept0102, Email = "[email protected]" },
 75                 new Person { Name = "汤富贵", Description = "广东", Department=dept0102,Email = "[email protected]" },
 76                 new Person { Name = "唐富贵", Description = "广东", Department=dept0102, Email = "[email protected]" },
 77                 new Person { Name = "唐蔚佳", Description = "广东", Department=dept0103,  Email = "[email protected]" },
 78                 new Person { Name = "谢显才", Description = "广东", Department=dept0103,Email = "[email protected]" },
 79                 new Person { Name = "解晓东", Description = "广东", Department=dept0103,  Email = "[email protected]" },
 80                 new Person { Name = "谢家麟", Description = "广东", Department=dept0103,Email = "[email protected]" },
 81                 new Person { Name = "谢子怡", Description = "广东", Department=dept0103, Email = "[email protected]" },
 82                 new Person { Name = "张建光", Description = "广东", Department=dept0103, Email = "[email protected]" },
 83                 new Person { Name = "李振书", Description = "广东", Department=dept0103,  Email = "[email protected]" },
 84                 new Person { Name = "陈丰州", Description = "广东", Department=dept0103, Email = "[email protected]" },
 85                 new Person { Name = "陈卫东", Description = "广东", Department=dept0103, Email = "[email protected]" },
 86                 new Person { Name = "陈峰受", Description = "广东", Department=dept0103, Email = "[email protected]" },
 87                 new Person { Name = "陈金健", Description = "广东", Department=dept0103,Email = "[email protected]" },
 88                 new Person { Name = "韦海波", Description = "广东", Department=dept0103, Email = "[email protected]" },
 89                 new Person { Name = "祁宣明", Description = "广东", Department=dept0103, Email = "[email protected]" },
 90                 new Person { Name = "戚计生", Description = "上海", Department=dept01,  Email = "[email protected]" },
 91                 new Person { Name = "石智生", Description = "广西", Department=dept0101,Email = "[email protected]" },
 92                 new Person { Name = "苏晓琳", Description = "广西", Department=dept0101,  Email = "[email protected]" },
 93                 new Person { Name = "苏振彪", Description = "广西", Department=dept0101, Email = "[email protected]" },
 94                 new Person { Name = "谭家伟", Description = "广西", Department=dept0101, Email = "[email protected]" },
 95                 new Person { Name = "谭俊杰", Description = "广西", Department=dept01,Email = "[email protected]" },
 96                 new Person { Name = "王定祠", Description = "广西", Department=dept01,  Email = "[email protected]" },
 97                 new Person { Name = "王金生", Description = "广西", Department=dept01,  Email = "[email protected]" },
 98                 new Person { Name = "王宝军", Description = "广西", Department=dept0103,  Email = "[email protected]" },
 99                 new Person { Name = "吴克标", Description = "广西", Department=dept0103, Email = "[email protected]" },
100                 new Person { Name = "吴斌", Description = "江西", Department=dept0103,  Email = "[email protected]" },
101                 new Person { Name = "游毅峰", Description = "湖南", Department=dept0103,  Email = "[email protected]" },
102                 new Person { Name = "柳君华", Description = "湖南", Department=dept0103,  Email = "[email protected]" },
103                 new Person { Name = "刘小薇", Description = "湖南", Department=dept0103,  Email = "[email protected]" },
104                 new Person { Name = "陈东风", Description = "湖南", Department=dept0103,  Email = "[email protected]" },
105                 new Person { Name = "欧阳海", Description = "湖南", Department=dept0103,  Email = "[email protected]" },
106                 new Person { Name = "柳三变", Description = "湖南", Department=dept0103,  Email = "[email protected]" },
107                 new Person { Name = "郭骁", Description = "北京", Department=dept0103,Email = "[email protected]" },
108                 new Person { Name = "郭家铭", Description = "香港", Department=dept0103,  Email = "[email protected]" },
109                 new Person { Name = "陈兆年", Description = "四川", Department=dept0103,  Email = "[email protected]mail.com" },
110                 new Person { Name = "农卫红", Description = "四川", Department=dept0103,  Email = "[email protected]" },
111                 new Person { Name = "农志升", Description = "四川", Department=dept0103,  Email = "[email protected]" },
112                 new Person { Name = "农小琳", Description = "四川", Department=dept0103, Email = "[email protected]" },
113                 new Person { Name = "徐荣国", Description = "四川", Department=dept0103,  Email = "[email protected]" },
114                 new Person { Name = "聂小威", Description = "四川", Department=dept0103,  Email = "[email protected]" },
115                 new Person { Name = "邱福林", Description = "四川", Department=dept0103,  Email = "[email protected]" },
116                 new Person { Name = "范思坦", Description = "四川", Department=dept0103,  Email = "[email protected]" },
117                 new Person { Name = "邓唯佳", Description = "四川", Department=dept0103, Email = "[email protected]" },
118                 new Person { Name = "马晓东", Description = "云南", Department=dept0103,  Email = "[email protected]" },
119                 new Person { Name = "魏明翠", Description = "云南", Department=dept0103,  Email = "[email protected]" },
120                 new Person { Name = "尹相杰", Description = "贵州", Department=dept0103,  Email = "[email protected]" },
121                 new Person { Name = "张小祎", Description = "贵州", Department=dept0103,  Email = "[email protected]" }
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

时间: 2024-11-05 14:38:34

part01.03 委托与 Lambda 表达式(三):Lambda 表达式的相关文章

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

delegate 是表示对具有特定参数列表和返回类型的方法的引用类型. 委托最大的作用就是为 类的事件 绑定 事件处理程序 可将任何可访问类或结构中与委托类型匹配的任何方法分配给委托.该方法可以是静态方法,也可以是实例方法.这样便能通过编程方式来更改方法调用,还可以向现有类中插入新代码. 将方法作为参数进行引用的能力使委托成为定义回调方法的理想选择. 将方法作为对象封装起来,允许在运行时间接地绑定一个方法调用. 在一定程度上可以把委托类型看成是定义了一个方法的接口,而委托的实例看成是对这个接口的

C++实现委托机制(三)——lambda表达式封装

C++实现委托机制(三)——lambda表达式封装1.引言:              其实原本没打算写这一章的,不过最后想了想,嗯还是把lambda表达式也一并封装进去,让这个委托也适应lambda表达式的注册.不过在之前还是需要先了解lambda表达式. 2.lambda表达式:              如果大家还有对lambda表达式不了解的可以先去了解lambda表达式的基本语法和用法.这里我们只讲跟lambda表达式封装相关的知识.我们先来看看使用lambda表达式的好处吧:1.la

委托,匿名方法,Lambda,泛型委托,表达式树

一.委托:完成一个委托应分三个步骤://step01:首先用delegate定义一个委托;public delegate int CalculatorAdd(int x, int y);//step02:声明一个方法来对应委托.public int Add(int x, int y){ return x + y;}protected void FrmTest_Load(object sender, EventArgs e){ //step03:用这个方法来实例化这个委托. CalculatorA

五分钟重温C#委托,匿名方法,Lambda,泛型委托,表达式树

五分钟重温C#委托,匿名方法,Lambda,泛型委托,表达式树 https://masuit.com/81 曾经新生代,好多都经过漫长的学习,理解,实践才能掌握委托,表达式树这些应用.今天我尝试用简单的方法叙述一下,让大家在五分钟内看完这篇博客 第一分钟:委托 有些教材,博客说到委托都会提到事件,虽然事件是委托的一个实例,但是为了理解起来更简单,今天只谈委托不谈事件.先上一段代码: 下边的代码,完成了一个委托应用的演示.一个委托分三个步骤: 1 2 3 4 5 6 7 8 9 10 11 12

3 委托、匿名函数、lambda表达式

委托.匿名函数.lambda表达式 在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法.C# 2.0 引入了匿名方法,而在 C# 3.0 及更高版本中,Lambda 表达式取代了匿名方法,作为编写内联代码的首选方式 // 声明一个委托 delegate void Printer(string s); class TestClass { static void Main() { //lambda表达式 Printer pp = x => { Console.WriteLine(&quo

委托、匿名委托、Lambda 表达式、Expression表达式树之刨根问底

本篇不是对标题所述之概念的入门文章,重点在阐述它们的异同点和应用场景.各位看官,这里就不啰嗦了,直接上代码. 首先定义一个泛型委托类型,如下: public delegate T Function<T>(T a, T b); 实现泛型委托的主体代码,并调用: public static string Add(string a, string b) { return string.Format("{0} #### {1}",a,b); } //实名委托方式 Function&

委托、匿名函数、Lambda表达式和事件的学习

委托: 还记得C++里的函数指针么?大家可以点击这里查看一下以前的笔记.C#的委托和C++中的函数指针效果一致. 当我们需要将函数作为对象进行传递和使用时就需要用到委托. 下面我们看一个例子: 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Test 8 { 9 cl

C#中分别对委托、匿名方法、Lambda表达式、Lambda表达式树以及反射执行同一方法的过程进行比较。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Linq.Expressions; namespace INPEXOne.LearnCS { class RefletLambdaDelegate { static object[] para

委托,匿名函数和lambda表达式

很早之前就接触到了委托,但是一直对他用的不是太多,主要是本人是菜鸟,能写的比较高级的代码确实不多,但是最近在看MSDN微软的类库的时候,发现了微软的类库好多都用到了委托,于是决定好好的研究研究,加深一下自己对他的印象,顺便把自己的感悟和想法写出来,以便自己能有更深的理解,由于本人水平有限,也欢迎大家多多探讨,有问题大家一起解决一起进步. MSDN上面对委托的定义是:delegate 是表示对具有特定参数列表和返回类型的方法的引用的类型.在我看来委托的特性主要在: 1.把一个方法当做一个参数传递给