C# 程式查詢序列的和


首先,設定一個序列。

List<int> myList = new List<int> { 1, 2, 3, 4 ,5};

現在使用可查詢的 Sum() 方法來查詢總和。

myList.AsQueryable().Sum();

示例

 線上演示

using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<int> myList = new List<int> { 1, 2, 3, 4 ,5};
      Console.WriteLine("Sum of elements in a list...");
      foreach (int res in myList) {
         Console.WriteLine(res);
      }
      int sum = myList.AsQueryable().Sum();
      Console.WriteLine("Sum = {0}", sum);
   }
}

輸出

Sum of elements in a list...
1
2
3
4
5
Sum = 15

更新日期: 2020 年 6 月 23 日

515 次瀏覽

開啟您的職業

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.