日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

C#使用Lambda表達式簡化代碼的示例詳解_C#教程

作者:dawn ? 更新時間: 2022-12-29 編程語言

Lambda,希臘字母λ,在C#編程語言中,被引入為Lambda表達式,表示為匿名函數(shù)(匿名方法)。

編程時離不開函數(shù),函數(shù)都有函數(shù)名和函數(shù)體,聲明函數(shù)名是為了方便多次使用,可是很多時候函數(shù)只使用一次,那么函數(shù)名就變得多余,這樣就產(chǎn)生了匿名函數(shù)(匿名方法)。

很多編程語言都有Lambde表達式,如Python、JavaScript、Java等等,這似乎是現(xiàn)代編程語言的標配了。

作為編程語言C#和編程環(huán)境Visual Stuidio的發(fā)展,總得不停地變幻出新花樣,功能還是那個功能或者略有增強,得益于編譯器的強大,C#3.0推出了Lambda表達式。

其實這些是非必要的,只是為C#編碼增加一些色彩和亮點而已,但是別人總喜歡這么寫,我們就得熟悉這些規(guī)則了。

舉例1:計算兩個整數(shù)的相加和相減。

① ?一般寫法

        //聲明變量
        private delegate int calculate(int x, int y);//聲明一個用于計算的委托類型
        private calculate MyCalculate;//聲明一個委托實例
 
        //聲明函數(shù)
        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 = $"兩數(shù)相加結(jié)果:{StrResultAdd}" + Environment.NewLine;
            textBox1.Text = textBox1.Text+ $"兩數(shù)相減結(jié)果:{StrResultReduce}" + Environment.NewLine;

② 使用自定義的委托

使用自定義的委托來使用Lamda可以讓代碼更簡潔:

            MyCalculate = delegate(int x,int y)
            {
                return x + y;
            };
            textBox1.Text = textBox1.Text+"兩數(shù)相加結(jié)果:" + MyCalculate(7, 2).ToString()+Environment.NewLine;
            MyCalculate = delegate (int x, int y)
            {
                return x - y;
            };
            textBox1.Text = textBox1.Text + "兩數(shù)相減結(jié)果:" + MyCalculate(7, 2).ToString() + Environment.NewLine;

上面得到的結(jié)果是一樣的。

③ 使用Func委托

FUNC委托的重載:

Func<TResult>;
Func<T1,T2,TResult>;
Func<T1,...,T16,TResult>;

使用系統(tǒng)內(nèi)置的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 + $"兩數(shù)相加結(jié)果:{MyAdd(7,2).ToString()}" + Environment.NewLine;
textBox1.Text = textBox1.Text + $"兩數(shù)相減結(jié)果:{MyReduce(7, 2).ToString()}" + Environment.NewLine;

④ 使用規(guī)范的Lambda表達式

更簡潔的寫法:

MyCalculate = (int x, int y) => { return x + y; };
textBox1.Text = textBox1.Text+$"兩數(shù)相加結(jié)果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
MyCalculate = (int x, int y) => { return x - y; };
textBox1.Text = textBox1.Text+$"兩數(shù)相減結(jié)果:{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 = $"兩數(shù)相加結(jié)果:{StrResultAdd}" + Environment.NewLine;
            textBox1.Text = textBox1.Text+ $"兩數(shù)相減結(jié)果:{StrResultReduce}" + Environment.NewLine;
            //2
            MyCalculate = delegate(int x,int y)
            {
                return x + y;
            };
            textBox1.Text = textBox1.Text+"兩數(shù)相加結(jié)果:" + MyCalculate(7, 2).ToString()+Environment.NewLine;
            MyCalculate = delegate (int x, int y)
            {
                return x - y;
            };
            textBox1.Text = textBox1.Text + "兩數(shù)相減結(jié)果:" + 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 + $"兩數(shù)相加結(jié)果:{MyAdd(7,2).ToString()}" + Environment.NewLine;
            textBox1.Text = textBox1.Text + $"兩數(shù)相減結(jié)果:{MyReduce(7, 2).ToString()}" + Environment.NewLine;
            //4
            MyCalculate = (int x, int y) => { return x + y; };
            textBox1.Text = textBox1.Text+$"兩數(shù)相加結(jié)果:{MyCalculate(7, 2).ToString()}" + Environment.NewLine;
            MyCalculate = (int x, int y) => { return x - y; };
            textBox1.Text = textBox1.Text+$"兩數(shù)相減結(jié)果:{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;
        }

結(jié)果顯示:

上面通過對比說明了Lambda表達式的應用,可以看出這樣的寫法相比傳統(tǒng)的寫法還是干凈利落,的確簡潔而優(yōu)雅一些。   

上面的可以改寫:

        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 + $"兩數(shù)相加結(jié)果:{MyCalculate1(7, 2,"+").ToString()}" + Environment.NewLine;
        textBox1.Text = textBox1.Text + $"兩數(shù)相減結(jié)果:{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 + $"兩數(shù)相加結(jié)果:{MyOperate(7, 2,"+").ToString()}" + Environment.NewLine;
            textBox1.Text = textBox1.Text + $"兩數(shù)相減結(jié)果:{MyOperate(7, 2,"-").ToString()}" + Environment.NewLine;

從上面的代碼演示中可以看出,Lambda與委托是緊密相連的。

舉例2:求幾個數(shù)的最大值與最小值。

① 一般寫法:

        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;
 
        //定義函數(shù)
        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();

到這里,我們看到這兩個方法只是判斷位置的代碼略有不同,其他的都相同,那么這個地方就可以使用委托來代替,就是把判斷方法當做參數(shù)傳進去。

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

顯示結(jié)果圖:

原文鏈接:https://blog.csdn.net/dawn0718/article/details/128132959

欄目分類
最近更新