Array ForEach Action

In this chapter you will learn:

  1. Array.ForEach with a delegate
  2. ForEach with your own delegate
  3. Use an Action to change the values

Array.ForEach with a delegate

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);
using System;/*from  j  av a2s  .  co 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;//from   ja va2s.  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;    
   //j  a  v a 2s.c o 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 j a  v  a  2  s. c  o m*/
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); 
  }       
}

Next chapter...

What you will learn in the next chapter:

  1. Get lowerbound and upperbound
Home » C# Tutorial » Array
Array
Array loop
Array dimension
Jagged Array
Array length
Array Index
Array rank
Array foreach loop
Array ForEach Action
Array lowerbound and upperbound
Array Sort
Array search with IndexOf methods
Array binary search
Array copy
Array clone
Array reverse
Array ConvertAll action
Array Find
Array SequenceEqual