Phương thức Sum() tính tổng các giá trị số trong một chuỗi. Hỗ trợ các kiểu: int, long, float, double, decimal.
Ví dụ minh họa
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("Các phần tử trong danh sách...");
foreach (int res in myList)
Console.WriteLine(res);
int sum = myList.AsQueryable().Sum();
Console.WriteLine("Tổng = {0}", sum);
}
}
Kết quả đầu ra
Các phần tử trong danh sách... 1 2 3 4 5 Tổng = 15
Lưu ý: Sum() ném ngoại lệ OverflowException nếu tổng vượt quá giới hạn kiểu dữ liệu. Sử dụng Sum(x => (long)x) để tránh tràn số với kiểu int.