Map, reduce, filter in C# Unity

· 1 min read

With the help of LINQ, we can easily do some functions like Map, Reduce and Filter like other languages.

Map

using System.Linq;

int[] values = new int[] {1, 2, 3, 4};
var newValues = values.Select( x => x*x).ToArray();  // [1, 4, 6, 16]   

Filter

using System.Linq;

int[] values = new int[] {1, 2, 3, 4};
var filterValues = values.Where( x => (x%2 == 0)).ToArray();  // [2, 4]

Reduce

using System.Linq;

var reduceValues = values.Aggregate((sum, next) => sum + next);  // 10

So instead of using the traditional for-loop, we can use map, filter, reduce above together to make the code more readable. For example, we can get the sum value of all even numbers of the above array:

using System.Linq;

int[] values = new int[] {1, 2, 3, 4};
var value = values.Where( x => (x%2 == 0)).Aggregate((sum, next) => sum + next);
// output: 6