You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Map, reduce, filter in C# Unity

Ben Liu
Ben Liu

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

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp