C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Action: The Action type (the second argument in ForEach) returns no value: it is void. It cannot directly modify elements.
ActionC# program that uses ForEach, WriteLine
using System;
class Program
{
static void Main()
{
int[] items = { 10, 100, 1000 };
// Display elements with ForEach.
Array.ForEach(items, element => Console.WriteLine(
"Element is " + element));
}
}
Output
Element is 10
Element is 100
Element is 1000
Here: This example program shows how to allocate a jagged array and then apply the Array.ForEach method with two arguments.
Jagged ArraysArguments: The arguments are the array itself, and a lambda expression that represents an Action type instance.
Lambda: The left part before the => token is the argument name, and the right part is the expression taken upon the argument.
LambdaInfo: The first array element in each subarray is modified. Usually, with ForEach, this style of code is not helpful.
C# program that uses Array.ForEach method
using System;
class Program
{
static void Main()
{
// 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();
}
}
}
Output
10
100
1000
20
200
2000
ToArray: A LINQ query, with the ToArray method, is an easier way to create a modified array.
ToArrayLINQThus: This method is not a "map" method. It is a loop abstraction, but not a good way to mutate every array element.