Đầu tiên, đặt danh sách -
List<int> myList = new List<int> () {
5,
10,
7
}; Bây giờ, hãy đặt giá trị của một biến thành 1 sẽ giúp chúng ta nhân -
int prod = 1;
Lặp lại và lấy sản phẩm -
foreach(int i in myList) {
prod = prod*i;
} Sau đây là mã -
Ví dụ
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List<int> myList = new List<int>() {
5,
10,
7
};
Console.WriteLine("List: ");
foreach(int i in myList) {
Console.WriteLine(i);
}
int prod = 1;
foreach(int i in myList) {
prod = prod*i;
}
Console.WriteLine("Product: {0}",prod);
}
} Đầu ra
List: 5 10 7 Product: 350