程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C# Lambda表達式使用累加器例子

C# Lambda表達式使用累加器例子

編輯:C#基礎知識
該例子源代碼摘自C#入門經典第5版第14章(387頁)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LambdaSample
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] myIntArray = { 1,2, 3, 4, 5 };
            //累加器計算數組總和
            int result = myIntArray.Aggregate((paramA, paramB) => paramA + paramB);
            int result1 = myIntArray.Aggregate<int>((paramA, paramB) => paramA + paramB);
            int result2 = myIntArray.Aggregate<int, int>(0, (paramA, paramB) => paramA + paramB);
            //遞歸計算數組總和
            int result3 = count(5);
            Console.WriteLine("The Result is: " + result);
            Console.WriteLine("The Result1 is: " + result1);
            Console.WriteLine("The Result2 is: " + result2);
            Console.WriteLine("The Result3 is: " + result3);

            string[] myStrArray = { "Admin", "Change", "ByPage" };
            //字符串數組拼接
            string strResult = myStrArray.Aggregate((paramA, paramB) => paramA + " " + paramB);
            //字符串數組字符串總長度計算
            int result4 = myStrArray.Aggregate<string, int>(0, (a, b) => a + b.Length);
            //字符串數組拼接2,增加字符串"Some curries: "
            string strResult1 = myStrArray.Aggregate<string, string>("Some curries: ", (a, b) => a + " " + b);
            //字符串數組字符串總長度計算2
            int result5 = myStrArray.Aggregate<string, string, int>("Some curries: ", (a, b) => a + " " + b, a => a.Length);
            Console.WriteLine("The StrResult is: " + strResult);
            Console.WriteLine("The Result4 is: " + result4);
            Console.WriteLine(strResult1);
            Console.WriteLine("The Result5 is: " + result5);
            Console.ReadKey();
        }

        static int count(int n)
        {
            if (n == 1)
            {
                return 1;
            }
            return n + count(n - 1);
        }
    }
}

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved