How to ForEach method and operate on each elements in a C# array

Description

You can enumerate using the static Array.ForEach method:

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

This uses an Action delegate, with this signature:

public delegate void Action<T> (T obj);

Example

Example for Array ForEach Action


using System;/*from  w w w.  j av  a 2  s  . c o m*/

public class MainClass{
    public static void Main(){
        int[] array = new int[] { 8, 2, 3, 5, 1, 3 };
        Array.ForEach<int>(array, delegate(int x) { Console.Write(x + " "); });
        Console.WriteLine();
    }
} 

The code above generates the following result.

We can further rewrite the code above as below.


using System;// w ww .j a v a 2 s  .co  m
using System.Collections;

class Sample
{
  public static void Main()
  {
    Array.ForEach(new[] { 1, 2, 3 }, Console.WriteLine);
  }
}

The output:

ForEach with your own delegate


using System;    
   //w  ww. j av  a2s  . co m
class MyClass { 
  public int i;  
   
  public MyClass(int x) { 
    i = x; 
  }
}
  
class MainClass {       
 
  static void show(MyClass o) { 
    Console.Write(o.i + " "); 
  } 
 
  public static void Main() {       
    MyClass[] nums = new MyClass[5];  
  
    nums[0] = new MyClass(5);  
    nums[1] = new MyClass(2);  
    nums[2] = new MyClass(3);  
    nums[3] = new MyClass(4);  
    nums[4] = new MyClass(1);  
     
    Console.Write("Contents of nums: ");   
 
    // Use action to show the values. 
    Array.ForEach(nums, MainClass.show); 
 
    Console.WriteLine();   
 
  }       
}

The code above generates the following result.

Change array element in a ForEach Action


using System;    
   //from   w ww .  java2  s .c om
class MyClass { 
  public int i;  
   
  public MyClass(int x) { 
    i = x; 
  }
}
  
class MainClass {       
 
  static void neg(MyClass o) {  
    o.i = -o.i; 
  }  
  static void show(MyClass o) { 
    Console.Write(o.i + " "); 
  } 
  public static void Main() {       
    MyClass[] nums = new MyClass[5];  
  
    nums[0] = new MyClass(5);  
    nums[1] = new MyClass(2);  
    nums[2] = new MyClass(3);  
    nums[3] = new MyClass(4);  
    nums[4] = new MyClass(1);  
     
    // Use action to negate the values. 
    Array.ForEach(nums, MainClass.neg); 
 
     // Use action to show the values. 
    Array.ForEach(nums, MainClass.show); 
  }       
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var