Khởi tạo List:
List<int> myList = new List<int>() { 5, 10, 7 };
Biến tích khởi tạo = 1, duyệt nhân dồn:
int prod = 1;
foreach (int i in myList)
{
prod = prod * i;
}
Ví dụ hoàn chỉnh
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> myList = new List<int>() { 5, 10, 7 };
Console.WriteLine("Danh sách:");
foreach (int i in myList)
Console.WriteLine(i);
int prod = 1;
foreach (int i in myList)
prod = prod * i;
Console.WriteLine("Tích: {0}", prod);
}
}
Kết quả
Danh sách: 5 10 7 Tích: 350
Cách thay thế LINQ: int prod = myList.Aggregate(1, (a, b) => a * b); (cần using System.Linq). Xử lý tràn số: cân nhắc dùng long hoặc BigInteger cho danh sách lớn.