Lambda/Linq用法

  • 272
  • 0
  • 2023-08-14

如何在用匿名函式, 處理Function/Action並取得結果
//Action: 可用ForEach
myList.ForEach(p => myFunc(p));
//Func:
IEnumerable範例
IEnumerable<DirectoryFileSegment> items =
    test
    //設定處理回傳的型別
    .Select(x => new Func<DirectoryFileSegment>(() =>                     
    {
    	//設定要呼叫的Function/Action及處理
        IList<string> directoryFileSegment = API.GetDirectorySegments(x); 
        if (directoryFileSegment != null) 
        {
                return new DirectoryFileSegment()
        		{...};
        }
		return null;
    }))
    //執行
    .Select(t => t?.Invoke())											 
    .AsEnumerable<DirectoryFileSegment>();
匿名函式,有以下用法
  • 變數x加1                            x => x+1
  • 回覆x是否等於y                 (x,y) => x == y
  • 若沒有參數, 可用空括號    () => (do something)

測試案例


    class Program
    {      

        //依需求將傳入兩個參數做加減乘除
	delegate int numOperation(int a,int b);

        static void Main(string[] args)
        {

		int x=2, y=3;

		calculator(x, y, (a,b)=>a+b);
		calculator(x, y, (a,b)=>a-b);
		calculator(x, y, (a,b)=>a*b);

	        Console.ReadLine();
        }

	    static void calculator(int x, int y, numOperation z)
	    {
		    Console.WriteLine(z(x,y));
	    }
    }

 

    class Program
    {
        delegate string getTransportation(int kilometer);

        static void Main(string[] args)
        {

            int x = 20;
            int y = 300;

            Console.WriteLine("哩程數大於100km搭飛機, 不然搭火車就好");
            theLogic(x);
            theLogic(y);
            Console.ReadLine();
        }

        static void theLogic(int kilometer)
        {
            getTransportation getvalue = new getTransportation(
                valueForTransportation => {
                    if (valueForTransportation > 100)
                    { return "搭飛機"; }
                    else
                    { return "搭火車"; }
                }
            );
            Console.WriteLine("哩程數為{0},所以{1}", kilometer.ToString(), getvalue(kilometer));
        }
    }