Phương thức Sum() của LINQ tính tổng các phần tử số trong collection. Ví dụ dưới đây minh họa với List
Ví dụ minh họa
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
List<int> list = new List<int> { 99, 34, 77, 75, 87, 35, 88 };
int res = list.AsQueryable().Sum();
Console.WriteLine("Tổng = {0}", res);
}
}
Kết quả đầu ra
Tổng = 495
Các nạp chồng (overloads):
Sum()- tổng trực tiếpSum(selector)- tổng sau khi biến đổi:list.Sum(x => x * 2)- Hỗ trợ: int, long, float, double, decimal và nullable types