• C#Lambda让代码变得更加简洁而优雅


      Using a lambda expression,we can make the code more compact and elegant。
      在使用lambda表达式时,可以使代码更加简洁和优雅。

      Lambda,希腊字母λ,在C#编程语言中,被引入为Lambda表达式,表示为匿名函数(匿名方法)。
      编程时离不开函数,函数都有函数名和函数体,声明函数名是为了方便多次使用,可是很多时候函数只使用一次,那么函数名就变得多余,这样就产生了匿名函数(匿名方法)。

      很多编程语言都有Lambde表达式,如Python、JavaScript、Java等等,这似乎是现代编程语言的标配了。
      作为编程语言C#和编程环境Visual Stuidio的发展,总得不停地变幻出新花样,功能还是那个功能或者略有增强,得益于编译器的强大,C#3.0推出了Lambda表达式。
      其实这些是非必要的,只是为C#编码增加一些色彩和亮点而已,但是别人总喜欢这么写,我们就得熟悉这些规则了。

      举例1:计算两个整数的相加和相减。

      ①  一般写法

    1. //声明变量
    2. private delegate int calculate(int x, int y);//声明一个用于计算的委托类型
    3. private calculate MyCalculate;//声明一个委托实例
    4. //声明函数
    5. private int Add(int x, int y)
    6. {
    7. return x+y;
    8. }
    9. private int Reduce(int x, int y)
    10. {
    11. return x - y;
    12. }

      就可以直接使用了。

    1. MyCalculate = new calculate(Add);
    2. string StrResultAdd = MyCalculate(7, 2).ToString();
    3. MyCalculate = new calculate(Reduce);
    4. string StrResultReduce = MyCalculate(7, 2).ToString();
    5. //
    6. textBox1.Text = $"两数相加结果:{StrResultAdd}" + Environment.NewLine;
    7. textBox1.Text = textBox1.Text+ $"两数相减结果:{StrResultReduce}" + Environment.NewLine;

      ② 使用自定义的委托

      使用自定义的委托来使用Lamda可以让代码更简洁:

    1. MyCalculate = delegate(int x,int y)
    2. {
    3. return x + y;
    4. };
    5. textBox1.Text = textBox1.Text+"两数相加结果:" + MyCalculate(7, 2).ToString()+Environment.NewLine;
    6. MyCalculate = delegate (int x, int y)
    7. {
    8. return x - y;
    9. };
    10. textBox1.Text = textBox1.Text + "两数相减结果:" + MyCalculate(7, 2).ToString() + Environment.NewLine;

      上面得到的结果是一样的。

      ③ 使用Func委托

      FUNC委托的重载:
      Func;
      Func;
      Func;
      使用系统内置的FUNC命名的委托来写LambDa表达式:

    1. Func<int,int,int> MyAdd = (int x, int y) => { return x + y; };
    2. Func<int, int, int> MyReduce = (int x, int y) => { return x - y; };
    3. textBox1.Text = textBox1.Text + $"两数相加结果:{MyAdd(7,2).ToString()}" + Environment.NewLine;
    4. textBox1.Text = textBox1.Text + $"两数相减结果:{MyReduce(7, 2).ToString()}" + Environment.NewLine;

      ④ 使用规范的Lambda表达式

      更简洁的写法:

    1. MyCalculate = (int x, int y) => { return x + y; };
    2. textBox1.Text = textBox1.Text+$"两数相加结果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
    3. MyCalculate = (int x, int y) => { return x - y; };
    4. textBox1.Text = textBox1.Text+$"两数相减结果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;

      完整代码:

    1. namespace Lambda
    2. {
    3. public partial class Form1 : Form
    4. {
    5. private delegate int calculate(int x, int y);//声明一个用于计算的委托类型
    6. private calculate MyCalculate;//声明一个委托实例
    7. public Form1()
    8. {
    9. InitializeComponent();
    10. }
    11. private void button1_Click(object sender, EventArgs e)
    12. {
    13. //1
    14. MyCalculate = new calculate(Add);
    15. string StrResultAdd = MyCalculate(7, 2).ToString();
    16. MyCalculate = new calculate(Reduce);
    17. string StrResultReduce = MyCalculate(7, 2).ToString();
    18. textBox1.Text = $"两数相加结果:{StrResultAdd}" + Environment.NewLine;
    19. textBox1.Text = textBox1.Text+ $"两数相减结果:{StrResultReduce}" + Environment.NewLine;
    20. //2
    21. MyCalculate = delegate(int x,int y)
    22. {
    23. return x + y;
    24. };
    25. textBox1.Text = textBox1.Text+"两数相加结果:" + MyCalculate(7, 2).ToString()+Environment.NewLine;
    26. MyCalculate = delegate (int x, int y)
    27. {
    28. return x - y;
    29. };
    30. textBox1.Text = textBox1.Text + "两数相减结果:" + MyCalculate(7, 2).ToString() + Environment.NewLine;
    31. //3
    32. Func<int,int,int> MyAdd = (int x, int y) => { return x + y; };
    33. Func<int, int, int> MyReduce = (int x, int y) => { return x - y; };
    34. textBox1.Text = textBox1.Text + $"两数相加结果:{MyAdd(7,2).ToString()}" + Environment.NewLine;
    35. textBox1.Text = textBox1.Text + $"两数相减结果:{MyReduce(7, 2).ToString()}" + Environment.NewLine;
    36. //4
    37. MyCalculate = (int x, int y) => { return x + y; };
    38. textBox1.Text = textBox1.Text+$"两数相加结果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
    39. MyCalculate = (int x, int y) => { return x - y; };
    40. textBox1.Text = textBox1.Text+$"两数相减结果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
    41. }
    42. private int Add(int x, int y)
    43. {
    44. return x+y;
    45. }
    46. private int Reduce(int x, int y)
    47. {
    48. return x - y;
    49. }

      结果显示:

      上面通过对比说明了Lambda表达式的应用,可以看出这样的写法相比传统的写法还是干净利落,的确简洁而优雅一些。   

      上面的可以改写:

    1. private delegate int calculate1(int x, int y,string str);//声明一个用于计算的委托类型
    2. private calculate1 MyCalculate1;//声明一个委托实例
    3. MyCalculate1 = (int x, int y,string StrOP) => {
    4. switch (StrOP)
    5. {
    6. case "+":
    7. return x + y; break;
    8. case "-": return x - y; break;
    9. default: return 0; break;
    10. }
    11. };
    12. textBox1.Text = textBox1.Text + $"两数相加结果:{MyCalculate1(7, 2,"+").ToString()}" + Environment.NewLine;
    13. textBox1.Text = textBox1.Text + $"两数相减结果:{MyCalculate1(7, 2,"-").ToString()}" + Environment.NewLine;

      或者:

    1. Func<int, int, string,int> MyOperate = (int x, int y, string StrOP) => {
    2. switch (StrOP)
    3. {
    4. case "+":
    5. return x + y; break;
    6. case "-": return x - y; break;
    7. default: return 0;break;
    8. }
    9. };
    10. textBox1.Text = textBox1.Text + $"两数相加结果:{MyOperate(7, 2,"+").ToString()}" + Environment.NewLine;
    11. textBox1.Text = textBox1.Text + $"两数相减结果:{MyOperate(7, 2,"-").ToString()}" + Environment.NewLine;

      从上面的代码演示中可以看出,Lambda与委托是紧密相连的或者说Lambda就是委托

      举例2:求几个数的最大值与最小值。

      ① 一般写法:

    1. private void button2_Click(object sender, EventArgs e)
    2. {
    3. textBox1.Text += "最大值:"+GetMax(new int[6]{7, 11,23,4,15,6}).ToString();
    4. textBox1.Text += Environment.NewLine;
    5. textBox1.Text += "最小值:" + GetMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
    6. }
    7. private static int GetMax(int[] Arr)
    8. {
    9. int ReturnValue = Arr[0];
    10. foreach( int a in Arr)
    11. {
    12. if(a > ReturnValue) ReturnValue = a;
    13. }
    14. return ReturnValue;
    15. }
    16. private static int GetMin(int[] Arr)
    17. {
    18. int ReturnValue = Arr[0];
    19. foreach (int a in Arr)
    20. {
    21. if (a < ReturnValue) ReturnValue = a;
    22. }
    23. return ReturnValue;
    24. }

      ② 使用委托来改写:

    1. //声明委托
    2. private delegate int GetMaxOrMin(int[] Arr);
    3. private GetMaxOrMin MyGetMaxOrMin;
    4. //定义函数
    5. private static int GetMax(int[] Arr)
    6. {
    7. int ReturnValue = Arr[0];
    8. foreach( int a in Arr)
    9. {
    10. if(a > ReturnValue) ReturnValue = a;
    11. }
    12. return ReturnValue;
    13. }
    14. private static int GetMin(int[] Arr)
    15. {
    16. int ReturnValue = Arr[0];
    17. foreach (int a in Arr)
    18. {
    19. if (a < ReturnValue) ReturnValue = a;
    20. }
    21. return ReturnValue;
    22. }
    23. //使用
    24. private void button2_Click(object sender, EventArgs e)
    25. {
    26. MyGetMaxOrMin = new GetMaxOrMin( GetMax);
    27. textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
    28. textBox1.Text += Environment.NewLine;
    29. MyGetMaxOrMin = new GetMaxOrMin(GetMin);
    30. textBox1.Text += "最小值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
    31. }

      ③ 使用自定义的委托

    1. MyGetMaxOrMin=delegate(int[] Arr)
    2. {
    3. int ReturnValue = Arr[0];
    4. foreach (int a in Arr)
    5. {
    6. if (a > ReturnValue) ReturnValue = a;
    7. }
    8. return ReturnValue;
    9. };
    10. textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
    11. MyGetMaxOrMin = delegate (int[] Arr)
    12. {
    13. int ReturnValue = Arr[0];
    14. foreach (int a in Arr)
    15. {
    16. if (a < ReturnValue) ReturnValue = a;
    17. }
    18. return ReturnValue;
    19. };
    20. textBox1.Text += "最小值:" + GetMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();

      到这里,我们看到这两个方法只是判断位置的代码略有不同,其他的都相同,那么这个地方就可以使用委托来代替,就是把判断方法当做参数传进去。

    1. private delegate Boolean Judge(int x,int y);//定义判断
    2. private Judge MyJudge;//实例化委托
    3. private delegate int GetMaxOrMin(int[] Arr,Judge j);//定义得到最大值或者最小值的计算方法
    4. private GetMaxOrMin MyGetMaxOrMin;//实例化
    5. private void button2_Click(object sender, EventArgs e)
    6. {
    7. MyGetMaxOrMin=delegate(int[] Arr,Judge MyJude)
    8. {
    9. int ReturnValue = Arr[0];
    10. foreach (int a in Arr)
    11. {
    12. if (MyJudge(a,ReturnValue)) ReturnValue = a;
    13. }
    14. return ReturnValue;
    15. };
    16. MyJudge = delegate (int x, int y) { return x > y; };
    17. textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 },MyJudge).ToString();
    18. MyJudge = delegate (int x, int y) { return x < y; };
    19. textBox1.Text += "最小值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 },MyJudge).ToString();
    20. }

      上面的写法的效果是一样的。

      ④ 使用Func委托

    1. Func<int[],Judge,int> MyGetMax = (int[] Arr,Judge MyJudge) => {
    2. int ReturnValue = Arr[0];
    3. foreach (int a in Arr)
    4. {
    5. if (MyJudge(a, ReturnValue)) ReturnValue = a;
    6. }
    7. return ReturnValue;
    8. };
    9. MyJudge = delegate (int x, int y) { return x > y; };
    10. textBox1.Text += "最大值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 },MyJudge).ToString();
    11. MyJudge = delegate (int x, int y) { return x < y; };
    12. textBox1.Text += "最小值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();

      ⑤ 使用更简洁的Lambda表达式

    1. var MyGetMaxOrMin1 = (int[] Arr,Judge J1 ) =>
    2. {
    3. int ReturnValue = Arr[0];
    4. foreach (int a in Arr)
    5. {
    6. if (J1(a, ReturnValue)) ReturnValue = a;
    7. }
    8. return ReturnValue;
    9. };
    10. Judge JudgeMax = (int x, int y) => { return x > y; };
    11. textBox1.Text += "最大值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMax).ToString();
    12. Judge JudgeMin = (int x, int y) => { return x < y; };
    13. textBox1.Text += "最小值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMin).ToString();

      或者:

    1. var MyGetMaxOrMin1 = (int[] Arr,Judge J1 ) =>
    2. {
    3. int ReturnValue = Arr[0];
    4. foreach (int a in Arr)
    5. {
    6. if (J1(a, ReturnValue)) ReturnValue = a;
    7. }
    8. return ReturnValue;
    9. };
    10. textBox1.Text += "最大值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, (int x, int y) => { return x > y; }).ToString();
    11. textBox1.Text += "最小值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, (int x, int y) => { return x < y; }).ToString();

      完整代码:

    1. using System.Collections.Generic;
    2. using System.Runtime.CompilerServices;
    3. using System.Security.Cryptography.X509Certificates;
    4. namespace Lambda
    5. {
    6. public partial class Form1 : Form
    7. {
    8. private delegate int calculate(int x, int y);//声明一个用于计算的委托类型
    9. private calculate MyCalculate;//声明一个委托实例
    10. private delegate int calculate1(int x, int y,string str);//声明一个用于计算的委托类型
    11. private calculate1 MyCalculate1;//声明一个委托实例
    12. private delegate Boolean Judge(int x,int y);
    13. private Judge MyJudge;
    14. private delegate int GetMaxOrMinA(int[] Arr);
    15. private GetMaxOrMinA MyGetMaxOrMinA;
    16. private delegate int GetMaxOrMin(int[] Arr,Judge j);
    17. private GetMaxOrMin MyGetMaxOrMin;
    18. public Form1()
    19. {
    20. InitializeComponent();
    21. }
    22. private void button2_Click(object sender, EventArgs e)
    23. {
    24. textBox1.Text += "最大值:" + GetMax(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
    25. textBox1.Text += "最小值:" + GetMin(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
    26. textBox1.Text += Environment.NewLine +"=====" + Environment.NewLine;
    27. MyGetMaxOrMinA = new GetMaxOrMinA(GetMax);
    28. textBox1.Text += "最大值:" + MyGetMaxOrMinA(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
    29. MyGetMaxOrMinA = new GetMaxOrMinA(GetMin);
    30. textBox1.Text += "最小值:" + MyGetMaxOrMinA(new int[6] { 7, 11, 23, 4, 15, 6 }).ToString();
    31. textBox1.Text += Environment.NewLine + "=====" + Environment.NewLine;
    32. MyGetMaxOrMin = delegate (int[] Arr, Judge MyJude)
    33. {
    34. int ReturnValue = Arr[0];
    35. foreach (int a in Arr)
    36. {
    37. if (MyJudge(a, ReturnValue)) ReturnValue = a;
    38. }
    39. return ReturnValue;
    40. };
    41. MyJudge = delegate (int x, int y) { return x > y; };
    42. textBox1.Text += "最大值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
    43. MyJudge = delegate (int x, int y) { return x < y; };
    44. textBox1.Text += "最小值:" + MyGetMaxOrMin(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
    45. textBox1.Text += Environment.NewLine +"=====" + Environment.NewLine;
    46. Func<int[], Judge, int> MyGetMax = (int[] Arr, Judge MyJudge) =>
    47. {
    48. int ReturnValue = Arr[0];
    49. foreach (int a in Arr)
    50. {
    51. if (MyJudge(a, ReturnValue)) ReturnValue = a;
    52. }
    53. return ReturnValue;
    54. };
    55. MyJudge = delegate (int x, int y) { return x > y; };
    56. textBox1.Text += "最大值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
    57. MyJudge = delegate (int x, int y) { return x < y; };
    58. textBox1.Text += "最小值:" + MyGetMax(new int[6] { 7, 11, 23, 4, 15, 6 }, MyJudge).ToString();
    59. textBox1.Text += Environment.NewLine +"=====" + Environment.NewLine;
    60. var MyGetMaxOrMin1 = (int[] Arr,Judge Judge1 ) =>
    61. {
    62. int ReturnValue = Arr[0];
    63. foreach (int a in Arr)
    64. {
    65. if (Judge1(a, ReturnValue)) ReturnValue = a;
    66. }
    67. return ReturnValue;
    68. };
    69. Judge JudgeMax = (int x, int y) => { return x > y; };
    70. textBox1.Text += "最大值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMax).ToString();
    71. Judge JudgeMin = (int x, int y) => { return x < y; };
    72. textBox1.Text += "最小值:" + MyGetMaxOrMin1(new int[6] { 7, 11, 23, 4, 15, 6 }, JudgeMin).ToString();
    73. }
    74. private static int GetMax(int[] Arr)
    75. {
    76. int ReturnValue = Arr[0];
    77. foreach( int a in Arr)
    78. {
    79. if(a > ReturnValue) ReturnValue = a;
    80. }
    81. return ReturnValue;
    82. }
    83. private static int GetMin(int[] Arr)
    84. {
    85. int ReturnValue = Arr[0];
    86. foreach (int a in Arr)
    87. {
    88. if (a < ReturnValue) ReturnValue = a;
    89. }
    90. return ReturnValue;
    91. }
    92. private static List<int> GetEven(List<int> list)
    93. {
    94. List<int> ReturnList =new List<int>();
    95. foreach (var a in list)
    96. {
    97. if (a %2 == 0) ReturnList.Add(a);
    98. }
    99. return ReturnList;
    100. }
    101. private static List<int> GetOdd(List<int> list)
    102. {
    103. List<int> ReturnList = new List<int>();
    104. foreach (var a in list)
    105. {
    106. if ( (a+1) % 2 == 0) ReturnList.Add(a);
    107. }
    108. return ReturnList;
    109. }
    110. }
    111. }

      显示结果图:

  • 相关阅读:
    Python + Django4 搭建个人博客(一) :搭建博客需要哪些技术,网站包括哪些内容
    Fill(填充)和Polygon(覆铜)盖油问题
    java基于微信小程序的社区高校失物招领系统 uniapp 小程序
    RK3568平台开发系列讲解(PCIE篇)PCIE驱动要如何学?
    Vue项目自动化部署 CI/CD
    docker搭建etcd集群
    Ajax:js绑定事件、ajax发送Get请求
    【毕业设计】MPU6050姿态解算 姿态估计 - 物联网 单片机 stm32
    Springboot导出Excel,支持大数据量
    基于Jsp的OA企业人事管理系统【论文、数据库设计、源码、开题报告】
  • 原文地址:https://blog.csdn.net/dawn0718/article/details/128132959