The Wayback Machine - https://web.archive.org/web/20240717024346/https://www.geeksforgeeks.org/c-sharp-performing-specified-action-on-each-element-of-array/
Open In App

C# | Performing Specified action on each element of Array

Last Updated : 06 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Array.ForEach(T[], Action<T>) Method is used to perform the specified action on each element of the specified array.
 

Syntax:  

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

Parameters: 

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.  

Exception: This method throws ArgumentNullException array is null or action is null.
Below programs illustrate the use of Array.ForEach(T[], Action) Method:
Example 1: 

CSHARP




// C# program to demonstrate
// Array.ForEach(T[], Action<T>)
// Method
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
 
        try {
 
            // Creating and initializing
            // new Array of int
            int[] myArr = { 2, 3, 4, 5 };
 
            // Display the values of the myArr.
            Console.Write("Initial Array: ");
 
            // calling the PrintIndexAndValues()
            // method to print
            PrintIndexAndValues(myArr);
 
            // set a delegate for
            // the SetSquares method
            Action<int> action = new Action<int>(SetSquares);
 
            // performing the action
            // using ForEach() method
            Array.ForEach(myArr, action);
        }
        catch (ArgumentNullException e) {
 
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
 
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(int[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
 
            Console.Write("{0} ", myArr[i]);
        }
        Console.WriteLine();
        Console.WriteLine();
    }
 
    // Defining the method
    // ShowSquares
    private static void SetSquares(int val)
    {
        Console.WriteLine("{0} squared = {1}",
                              val, val * val);
    }
}


Output: 

Initial Array: 2 3 4 5 

2 squared = 4
3 squared = 9
4 squared = 16
5 squared = 25

 

Example 2:

CSHARP




// C# program to demonstrate
// Array.ForEach(T[], Action<T>)
// Method
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Main Method
    public static void Main()
    {
 
        try {
 
            // Creating and initializing
            // new Array of with null
            int[] myArr = null;
 
            // set a delegate for
            // the Set Squares method
            Action<int> action = new Action<int>(SetSquares);
 
            // performing the action
            // using ForEach() method
            Console.WriteLine("Trying to perform "
                       +"action on a null Array");
            Console.WriteLine();
            Array.ForEach(myArr, action);
        }
        catch (ArgumentNullException e) {
 
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
 
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(int[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
 
            Console.Write("{0} ", myArr[i]);
        }
        Console.WriteLine();
        Console.WriteLine();
    }
 
    // Defining the method
    // ShowSquares
    private static void SetSquares(int val)
    {
        Console.WriteLine("{0} squared = {1}", val, val * val);
    }
}


Output: 

Trying to perform action on a null Array

Exception Thrown: System.ArgumentNullException

 

Reference: 



Similar Reads

C# | How to perform a specified action on each element of the List
List&lt;T&gt;.ForEach(Action&lt;T&gt;) Method is used to perform a specified action on each element of the List&lt;T&gt;. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count become
2 min read
C# | Insert an element into the ArrayList at the specified index
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Insert(Int32, Object) method inserts an element into the ArrayList at the specified index. Properties of ArrayList
3 min read
C# | Check if a HashSet contains the specified element
A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.Contains(T) Method is used to check whether a HashS
2 min read
C# | Remove the element with the specified key from the Hashtable
The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Remove(Object) Method is used to remove the element with the specified key from the Hashtable. Syntax: public virtual void Remove (object key); Parameter: key: It i
2 min read
C# | Removing the specified element from the List
List.Remove(T) Method is used to remove the first occurrence of a specific object from the List. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then
2 min read
C# | Remove the specified element from a HashSet
A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet&lt;T&gt;.Remove(T) method is used to remove the spe
3 min read
C# | Gets or Sets the element at the specified index in the List
List&lt;T&gt;.Item[Int32] Property is used to gets or sets the element at the specified index. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then t
2 min read
C# | Remove the element at the specified index of the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveAt(Int32) method is used to remove the element at the specified index of the ArrayList. Properties: Elements
3 min read
C# | How to remove the element from the specified index of the List
List&lt;T&gt;.RemoveAt (Int32) Method is used to remove the element at the specified index of the List&lt;T&gt;. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals
3 min read
C# | How to get the last occurrence of the element in the List that match the specified conditions
List&lt;T&gt;.FindLast(Predicate&lt;T&gt;) Method is used to search for an element which matches the conditions defined by the specified predicate and it returns the last occurrence of that element within the entire List&lt;T&gt;. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot.List class can
4 min read
Article Tags :
three90RightbarBannerImg