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

Linqを使ってList(リスト)の全要素で掛け算するには、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
}
}
コメント