C# 程序用于查找序列的总和

csharpprogrammingserver side programming更新于 2025/9/14 5:48:00

首先,设置一个序列。

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

现在使用 Queryable 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("列表中元素的总和...");
      foreach (int res in myList) {
         Console.WriteLine(res);
      }
      int sum = myList.AsQueryable().Sum();
      Console.WriteLine("Sum = {0}", sum);
   }
}

输出

列表中元素的总和...
1
2
3
4
5
Sum = 15

相关文章