どうも、ちょげ(@chogetarou)です。
List(リスト)の全要素で掛け算する方法を紹介します。
方法

List(リスト)の全要素で掛け算する方法は、2つあります。
foreach
1つは、foreachを使う方法です。
まず、掛け算した結果を格納する変数を用意します。
var result = 1;
そして、foreachでListをループします。
ループ処理で、Listの要素を用意した変数に掛け算します。
foreach (var x in list) {
result *= x;
}
上記のforeachの処理後に、用意した変数にListの全要素で掛け算した値が格納されます。
使用例
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>{ 1, 2, 3, 4, 5 };
int result = 1;
foreach (var i in numbers) {
result *= i;
}
Console.WriteLine(result); //120
}
}
LinqのAggregate
もう1つは、System.LinqのAggregateを使う方法です。
まず、Sytem.Linqを導入します。
using System.Linq;
そして、ListからAggregate()を呼び出します。
Aggregateの引数に、2つの引数の積を返すラムダ式を指定します。
var result = list.Aggregate((x, y) => x * y);
上記のAggregate()は、呼び出したListの全要素で掛け算した値を返します。
使用例
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>{ 1, 2, 3, 4, 5 };
int result = numbers.Aggregate((x, y) => x * y);
Console.WriteLine(result); //120
}
}
まとめ
List(リスト)の全要素で掛け算する方法は、次の2つです。
- foreachを使う方法
- System.LinqのAggregate()を使う方法
コメント