C#でmap、filter、reduce
「Googleを支える技術」で?一躍有名になった感がするmap、filter、reduceですが、LINQ(C#)で対応させると以下になるんでしょか?
一般? | LINQ(C#) |
---|---|
map | Select |
filter | Where |
reduce | Aggregate |
せっかくneueccさんがAggregateの良いサンプルを書いてくださったので、Aggregateの復習も兼ねてさらっと。
class Program { public static void Main(string[] args) { Console.WriteLine(Enumerable.Range(1, 10) .Select(num => num * num) .Where(num => num % 2 == 0) .Aggregate((sum, num) => sum + num)); //220 Console.ReadLine(); } }
アルゴリズム自体は以下の流れ。
- Range : 1〜10の整数列の生成
- Select : 1〜10を各々二乗する
- Where : 偶数の値のみにフィルタする
- Aggregate : 整数列の値を畳み込む
めっさシンプル。