Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# หาผลรวมของลำดับข้อมูล

ขั้นแรก ให้กำหนดลำดับข้อมูล (sequence):

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("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