Array.ForEach
This C# method loops over every element. It calls another method on each element in an array. ForEach()
is a declarative syntax form—this simplifies certain code patterns.
Usually the Array.ForEach
method is mostly used on arrays of objects. Each object has a method we want to invoke, and we use a lambda to call that method.
Class
exampleHere we create an array of class
instances with an initializer expression. Each Dog object has an Add()
method that we want to call.
Size
of each dog to a certain integer.ForEach
method calls the lambda (second argument) on each Dog instance we created. Each Dog's size is incremented.using System; class Dog { public int Size { get; set; } public void Add() { this.Size++; } } class Program { static void Main() { // Create array of objects. var dogs = new Dog[]{ new Dog(){ Size = 1 }, new Dog(){ Size = 3 } }; // Call method on each object. Array.ForEach(dogs, dog => dog.Add()); Console.WriteLine("DONE"); } }DONE
Console
exampleNext we call Array.ForEach
on an int
array. We cannot modify values within the array, but we can act upon them or pass them to a Console
static
method.
ForEach
) returns no value: it is void
. It cannot directly modify elements.using System; int[] items = { 10, 100, 1000 }; // Display elements with ForEach. Array.ForEach(items, element => Console.WriteLine("Element is " + element));Element is 10 Element is 100 Element is 1000
ForEach
uses an Action type as its second argument. We can modify elements in nested jagged arrays with Array.ForEach
.
Array.ForEach
method with 2 arguments.ForEach
, this style of code is not helpful.using System; // Allocate a jagged array and put 3 subarrays into it. int[][] array = new int[3][]; array[0] = new int[2]; array[1] = new int[3]; array[2] = new int[4]; // Use ForEach to modify each subarray's first element. // ... Because the closure variable is an array reference, you can change it. Array.ForEach(array, subarray => subarray[0]++); foreach (int[] subarray in array) { foreach (int i in subarray) { Console.Write(i); } Console.WriteLine(); } // Apply the same routine with ForEach again. Array.ForEach(array, subarray => subarray[0]++); foreach (int[] subarray in array) { foreach (int i in subarray) { Console.Write(i); } Console.WriteLine(); }10 100 1000 20 200 2000
The Action delegate receives a formal parameter list. These arguments are copied by value. When we copy an element of an array as a parameter, it becomes a scalar variable.
ForEach
, we cannot directly modify array elements. The change is not reflected in the array.Array.ForEach
is not a "map" method. It is a loop abstraction, but not a good way to mutate every array element.ToArray
method, is an easier way to create a modified array.Array.ForEach
is a declarative loop. By applying this method, we can invoke a method on each array element. Or we can modify something based on a reference (class
) element.