どうも、ちょげ(@chogetarou)です。
List(リスト)の指定した条件を満たす要素の合計値を取得する方法を紹介します。
方法

Listの条件に合致する要素の合計値を取得するには、Where()とSum()を使います。
まず、System.Linqを導入します。
using System.Linq;
次に、ListからWhere()を呼び出します。
Whereのラムダ式で条件を返します。
そして、Where()からSum()を呼び出します。
var sum = list.Where(x => 条件式).Sum();
上記のSum()は、Whereのラムダ式の条件式で「True」を返した要素の合計値を返します。
使用例
using System;
using System.Linq;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>() {1, 2, 3, 4, 5, 6, 7, 8};
//偶数の合計値を取得
int sum = numbers.Where(x => x % 2 == 0).Sum();
Console.WriteLine(sum); //20
}
}
コメント