C#使用Lambda表达式简化代码的示例详解
作者:dawn 发布时间:2022-09-16 03:03:36
Lambda,希腊字母λ,在C#编程语言中,被引入为Lambda表达式,表示为匿名函数(匿名方法)。
编程时离不开函数,函数都有函数名和函数体,声明函数名是为了方便多次使用,可是很多时候函数只使用一次,那么函数名就变得多余,这样就产生了匿名函数(匿名方法)。
很多编程语言都有Lambde表达式,如Python、JavaScript、Java等等,这似乎是现代编程语言的标配了。
作为编程语言C#和编程环境Visual Stuidio的发展,总得不停地变幻出新花样,功能还是那个功能或者略有增强,得益于编译器的强大,C#3.0推出了Lambda表达式。
其实这些是非必要的,只是为C#编码增加一些色彩和亮点而已,但是别人总喜欢这么写,我们就得熟悉这些规则了。
举例1:计算两个整数的相加和相减。
① 一般写法
//声明变量
private delegate int calculate(int x, int y);//声明一个用于计算的委托类型
private calculate MyCalculate;//声明一个委托实例
//声明函数
private int Add(int x, int y)
{
return x+y;
}
private int Reduce(int x, int y)
{
return x - y;
}
就可以直接使用了。
MyCalculate = new calculate(Add);
string StrResultAdd = MyCalculate(7, 2).ToString();
MyCalculate = new calculate(Reduce);
string StrResultReduce = MyCalculate(7, 2).ToString();
//
textBox1.Text = $"两数相加结果:{StrResultAdd}" + Environment.NewLine;
textBox1.Text = textBox1.Text+ $"两数相减结果:{StrResultReduce}" + Environment.NewLine;
② 使用自定义的委托
使用自定义的委托来使用Lamda可以让代码更简洁:
MyCalculate = delegate(int x,int y)
{
return x + y;
};
textBox1.Text = textBox1.Text+"两数相加结果:" + MyCalculate(7, 2).ToString()+Environment.NewLine;
MyCalculate = delegate (int x, int y)
{
return x - y;
};
textBox1.Text = textBox1.Text + "两数相减结果:" + MyCalculate(7, 2).ToString() + Environment.NewLine;
上面得到的结果是一样的。
③ 使用Func委托
FUNC委托的重载:
Func<TResult>;
Func<T1,T2,TResult>;
Func<T1,...,T16,TResult>;
使用系统内置的FUNC命名的委托来写LambDa表达式:
Func<int,int,int> MyAdd = (int x, int y) => { return x + y; };
Func<int, int, int> MyReduce = (int x, int y) => { return x - y; };
textBox1.Text = textBox1.Text + $"两数相加结果:{MyAdd(7,2).ToString()}" + Environment.NewLine;
textBox1.Text = textBox1.Text + $"两数相减结果:{MyReduce(7, 2).ToString()}" + Environment.NewLine;
④ 使用规范的Lambda表达式
更简洁的写法:
MyCalculate = (int x, int y) => { return x + y; };
textBox1.Text = textBox1.Text+$"两数相加结果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
MyCalculate = (int x, int y) => { return x - y; };
textBox1.Text = textBox1.Text+$"两数相减结果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
完整代码:
namespace Lambda
{
public partial class Form1 : Form
{
private delegate int calculate(int x, int y);//声明一个用于计算的委托类型
private calculate MyCalculate;//声明一个委托实例
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//1
MyCalculate = new calculate(Add);
string StrResultAdd = MyCalculate(7, 2).ToString();
MyCalculate = new calculate(Reduce);
string StrResultReduce = MyCalculate(7, 2).ToString();
textBox1.Text = $"两数相加结果:{StrResultAdd}" + Environment.NewLine;
textBox1.Text = textBox1.Text+ $"两数相减结果:{StrResultReduce}" + Environment.NewLine;
//2
MyCalculate = delegate(int x,int y)
{
return x + y;
};
textBox1.Text = textBox1.Text+"两数相加结果:" + MyCalculate(7, 2).ToString()+Environment.NewLine;
MyCalculate = delegate (int x, int y)
{
return x - y;
};
textBox1.Text = textBox1.Text + "两数相减结果:" + MyCalculate(7, 2).ToString() + Environment.NewLine;
//3
Func<int,int,int> MyAdd = (int x, int y) => { return x + y; };
Func<int, int, int> MyReduce = (int x, int y) => { return x - y; };
textBox1.Text = textBox1.Text + $"两数相加结果:{MyAdd(7,2).ToString()}" + Environment.NewLine;
textBox1.Text = textBox1.Text + $"两数相减结果:{MyReduce(7, 2).ToString()}" + Environment.NewLine;
//4
MyCalculate = (int x, int y) => { return x + y; };
textBox1.Text = textBox1.Text+$"两数相加结果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
MyCalculate = (int x, int y) => { return x - y; };
textBox1.Text = textBox1.Text+$"两数相减结果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
}
private int Add(int x, int y)
{
return x+y;
}
private int Reduce(int x, int y)
{
return x - y;
}
结果显示:
上面通过对比说明了Lambda表达式的应用,可以看出这样的写法相比传统的写法还是干净利落,的确简洁而优雅一些。
上面的可以改写:
private delegate int calculate1(int x, int y,string str);//声明一个用于计算的委托类型
private calculate1 MyCalculate1;//声明一个委托实例
MyCalculate1 = (int x, int y,string StrOP) => {
switch (StrOP)
{
case "+":
return x + y; break;
case "-": return x - y; break;
default: return 0; break;
}
};
textBox1.Text = textBox1.Text + $"两数相加结果:{MyCalculate1(7, 2,"+").ToString()}" + Environment.NewLine;
textBox1.Text = textBox1.Text + $"两数相减结果:{MyCalculate1(7, 2,"-").ToString()}" + Environment.NewLine;
或者:
Func<int, int, string,int> MyOperate = (int x, int y, string StrOP) => {
switch (StrOP)
{
case "+":
return x + y; break;
case "-": return x - y; break;
default: return 0;break;
}
};
textBox1.Text = textBox1.Text + $"两数相加结果:{MyOperate(7, 2,"+").ToString()}" + Environment.NewLine;
textBox1.Text = textBox1.Text + $"两数相减结果:{MyOperate(7, 2,"-").ToString()}" + Environment.NewLine;
从上面的代码演示中可以看出,Lambda与委托是紧密相连的。
举例2:求几个数的最大值与最小值。
① 一般写法:
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text += "最大值:"+GetMax(new int[6]{7, 11,23,4,15,6}).ToString();
textBox1.Text += Environment.NewLine;
textBox1.Text += "最小值:" + GetMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
}
private static int GetMax(int[] Arr)
{
int ReturnValue = Arr[0];
foreach( int a in Arr)
{
if(a > ReturnValue) ReturnValue = a;
}
return ReturnValue;
}
private static int GetMin(int[] Arr)
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (a < ReturnValue) ReturnValue = a;
}
return ReturnValue;
}
② 使用委托来改写:
//声明委托
private delegate int GetMaxOrMin(int[] Arr);
private GetMaxOrMin MyGetMaxOrMin;
//定义函数
private static int GetMax(int[] Arr)
{
int ReturnValue = Arr[0];
foreach( int a in Arr)
{
if(a > ReturnValue) ReturnValue = a;
}
return ReturnValue;
}
private static int GetMin(int[] Arr)
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (a < ReturnValue) ReturnValue = a;
}
return ReturnValue;
}
//使用
private void button2_Click(object sender, EventArgs e)
{
MyGetMaxOrMin = new GetMaxOrMin( GetMax);
textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
textBox1.Text += Environment.NewLine;
MyGetMaxOrMin = new GetMaxOrMin(GetMin);
textBox1.Text += "最小值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
}
③ 使用自定义的委托
MyGetMaxOrMin=delegate(int[] Arr)
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (a > ReturnValue) ReturnValue = a;
}
return ReturnValue;
};
textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
MyGetMaxOrMin = delegate (int[] Arr)
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (a < ReturnValue) ReturnValue = a;
}
return ReturnValue;
};
textBox1.Text += "最小值:" + GetMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
到这里,我们看到这两个方法只是判断位置的代码略有不同,其他的都相同,那么这个地方就可以使用委托来代替,就是把判断方法当做参数传进去。
private delegate Boolean Judge(int x,int y);//定义判断
private Judge MyJudge;//实例化委托
private delegate int GetMaxOrMin(int[] Arr,Judge j);//定义得到最大值或者最小值的计算方法
private GetMaxOrMin MyGetMaxOrMin;//实例化
private void button2_Click(object sender, EventArgs e)
{
MyGetMaxOrMin=delegate(int[] Arr,Judge MyJude)
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (MyJudge(a,ReturnValue)) ReturnValue = a;
}
return ReturnValue;
};
MyJudge = delegate (int x, int y) { return x > y; };
textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 },MyJudge).ToString();
MyJudge = delegate (int x, int y) { return x < y; };
textBox1.Text += "最小值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 },MyJudge).ToString();
}
上面的写法的效果是一样的。
④ 使用Func委托
Func<int[],Judge,int> MyGetMax = (int[] Arr,Judge MyJudge) => {
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (MyJudge(a, ReturnValue)) ReturnValue = a;
}
return ReturnValue;
};
MyJudge = delegate (int x, int y) { return x > y; };
textBox1.Text += "最大值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 },MyJudge).ToString();
MyJudge = delegate (int x, int y) { return x < y; };
textBox1.Text += "最小值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
⑤ 使用更简洁的Lambda表达式
var MyGetMaxOrMin1 = (int[] Arr,Judge J1 ) =>
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (J1(a, ReturnValue)) ReturnValue = a;
}
return ReturnValue;
};
Judge JudgeMax = (int x, int y) => { return x > y; };
textBox1.Text += "最大值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMax).ToString();
Judge JudgeMin = (int x, int y) => { return x < y; };
textBox1.Text += "最小值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMin).ToString();
完整代码:
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
namespace Lambda
{
public partial class Form1 : Form
{
private delegate int calculate(int x, int y);//声明一个用于计算的委托类型
private calculate MyCalculate;//声明一个委托实例
private delegate int calculate1(int x, int y,string str);//声明一个用于计算的委托类型
private calculate1 MyCalculate1;//声明一个委托实例
private delegate Boolean Judge(int x,int y);
private Judge MyJudge;
private delegate int GetMaxOrMinA(int[] Arr);
private GetMaxOrMinA MyGetMaxOrMinA;
private delegate int GetMaxOrMin(int[] Arr,Judge j);
private GetMaxOrMin MyGetMaxOrMin;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text += "最大值:" + GetMax(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
textBox1.Text += "最小值:" + GetMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
textBox1.Text += Environment.NewLine +"=====" + Environment.NewLine;
MyGetMaxOrMinA = new GetMaxOrMinA(GetMax);
textBox1.Text += "最大值:" + MyGetMaxOrMinA(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
MyGetMaxOrMinA = new GetMaxOrMinA(GetMin);
textBox1.Text += "最小值:" + MyGetMaxOrMinA(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
textBox1.Text += Environment.NewLine + "=====" + Environment.NewLine;
MyGetMaxOrMin = delegate (int[] Arr, Judge MyJude)
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (MyJudge(a, ReturnValue)) ReturnValue = a;
}
return ReturnValue;
};
MyJudge = delegate (int x, int y) { return x > y; };
textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
MyJudge = delegate (int x, int y) { return x < y; };
textBox1.Text += "最小值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
textBox1.Text += Environment.NewLine +"=====" + Environment.NewLine;
Func<int[], Judge, int> MyGetMax = (int[] Arr, Judge MyJudge) =>
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (MyJudge(a, ReturnValue)) ReturnValue = a;
}
return ReturnValue;
};
MyJudge = delegate (int x, int y) { return x > y; };
textBox1.Text += "最大值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
MyJudge = delegate (int x, int y) { return x < y; };
textBox1.Text += "最小值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
textBox1.Text += Environment.NewLine +"=====" + Environment.NewLine;
var MyGetMaxOrMin1 = (int[] Arr,Judge Judge1 ) =>
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (Judge1(a, ReturnValue)) ReturnValue = a;
}
return ReturnValue;
};
Judge JudgeMax = (int x, int y) => { return x > y; };
textBox1.Text += "最大值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMax).ToString();
Judge JudgeMin = (int x, int y) => { return x < y; };
textBox1.Text += "最小值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMin).ToString();
}
private static int GetMax(int[] Arr)
{
int ReturnValue = Arr[0];
foreach( int a in Arr)
{
if(a > ReturnValue) ReturnValue = a;
}
return ReturnValue;
}
private static int GetMin(int[] Arr)
{
int ReturnValue = Arr[0];
foreach (int a in Arr)
{
if (a < ReturnValue) ReturnValue = a;
}
return ReturnValue;
}
private static List<int> GetEven(List<int> list)
{
List<int> ReturnList =new List<int>();
foreach (var a in list)
{
if (a %2 == 0) ReturnList.Add(a);
}
return ReturnList;
}
private static List<int> GetOdd(List<int> list)
{
List<int> ReturnList = new List<int>();
foreach (var a in list)
{
if ( (a+1) % 2 == 0) ReturnList.Add(a);
}
return ReturnList;
}
}
}
显示结果图:
来源:https://blog.csdn.net/dawn0718/article/details/128132959


猜你喜欢
- 下面给大家介绍C#使用ICSharpCode.SharpZipLib.dll进行文件的压缩与解压功能,具体代码如下所示:using Syst
- 背景在写一个东西滑动删除列表的时候,出现了一个问题。我的需求是,左滑然后出现delete,然后点击delete,让该滑块消失。我在点列表的第
- 前言Graalvm通过静态分析提前编译来为Java应用程序构建高度优化的本机可执行文件,这就需要在编译时就知道所有的程序类型,而java中的
- 本篇博客要分享的一个UI效果——实现底部切换标签,想必大家在一些应用上面遇到过这种效果了,最典型的就是微信了,可以左右滑动切换页面,也可以点
- 本文以实例形式展示了基于C#实现Windows服务状态启动和停止服务的方法。非常实用。分享给大家供大家参考之用。具体方法如下:首先先引用:S
- 先介绍下一些基本定义串行通信:通过的是PLC上的串行口RS232/RS422/485口,上位机链接系统 Hostlink系统是对于FA系统一
- 本文实例讲述了C#实现导入CSV文件到Excel工作簿的方法。分享给大家供大家参考。具体如下:你必须在项目中添加对 Microsoft.Of
- 在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口;Thread类是在java.lang包中定义的
- 前言: 在命令行中输入可以输入各类参数,本文将针对这些参数做一个小结。基于命令行输入参数测试程序如下:import java.util.Ar
- 导入项目集成环境:IntelliJ IDEA 2020.1.2演示系统:DELL Windows 10Eclipse项目如何导入IDEA并成
- 树形结构很多地方都有应用,比如我们在构造网站后台的授权限树的时候,再比如我们在设计多级留言的时候、还有分类等等。有些时候我们的树形结构并不需
- 一、创建springboot项目(采用骨架方式)创建完成;我们分析下pom文件中内容:所使用到的关键依赖: <!--springBoo
- 前言如今发短信功能已经成为互联网公司的标配,本篇文章将一步步实现java发送短信考察了许多提供短信服务的三方,几乎所有都需要企业认证才可以使
- 结构体是由一系列具有相同类型或不同类型的数据构成的数据集合。所以,标准C中的结构体是不允许包含成员函数的,当然C++中的结构体对此进行了扩展
- 一、事件背景个人感觉自己做性能测试,可以说是轻车熟路了,而且工作多年一直都是这一套测试思路及体系,从未质疑过自己,也许是狮子座的迷之自信吧!
- java jdbc连接和使用jdbc导入驱动//jar是已经打包好的class文件集,可以引用到其他工程中 //Build Pa
- 本文介绍的是关于Mybatis中用OGNL表达式处理动态sql的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:常用的Mybat
- 我们将会从以下的几点理解java线程的一些概念:线程的基本概念和优劣之处创建一个线程的两种方式线程的属性线程的状态synchronized可
- 前言:项目是使用Java swing开发,可实现基础数据维护用户登录、系统首页酒店信息管理、主要模块是开房管理、退房管理、房间信息管理、顾客
- HTTPclient保持长连接首先解释一下什么是长连接当我们向一台服务器发起请求时,我们需要和对方建立一条通道,去传输数据,所谓的短连接,就