C# Array ForEach

Description

Array ForEach performs the specified action on each element of the specified array.

Syntax

Array.ForEach has the following syntax.


public static void ForEach<T>(
  T[] array,
  Action<T> action
)

Parameters

Array.ForEach has the following parameters.

  • T - The type of the elements of the array.
  • array - The one-dimensional, zero-based Array on whose elements the action is to be performed.
  • action - The Action to perform on each element of array.

Returns

Array.ForEach method returns

Example

The following example shows how to use ForEach to display the squares of each element in an integer array.


using System;//w  w w.ja  va  2s  .c  o m

public class SamplesArray
{
    public static void Main()
    {
        int[] intArray = new int[] {2, 3, 4};

        Action<int> action = new Action<int>(ShowSquares);

        Array.ForEach(intArray, action);
    }

    private static void ShowSquares(int val)
    {
        Console.WriteLine("{0:d} squared = {1:d}", val, val*val);
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version