Open In App

C# | How to perform a specified action on each element of the List

List<T>.ForEach(Action<T>) Method is used to perform a specified action on each element of the List<T>.

Properties of List:



Syntax:

public void ForEach (Action action);

Parameter:



action: It is the Action<T> delegate to perform on each element of the List<T>.

Exceptions:

Below programs illustrate the use List<T>.ForEach(Action<T>) Method:

Example 1:




// C# Program to perform a specified
// action on each element of the List<T>
using System;
using System.Collections;
using System.Collections.Generic;
  
class Geeks {
  
    // display method
    static void display(string str)
    {
        Console.WriteLine(str);
    }
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating an List<T> of strings
        List<String> firstlist = new List<String>();
  
        // Adding elements to List
        firstlist.Add("Geeks");
        firstlist.Add("For");
        firstlist.Add("Geeks");
        firstlist.Add("GFG");
        firstlist.Add("C#");
        firstlist.Add("Tutorials");
        firstlist.Add("GeeksforGeeks");
  
        // using ForEach Method
        // which calls display method
        // on each element of the List
        firstlist.ForEach(display);
    }
}

Output:

Geeks
For
Geeks
GFG
C#
Tutorials
GeeksforGeeks

Example 2:




// C# Program to perform a specified
// action on each element of the List<T>
using System;
using System.Collections;
using System.Collections.Generic;
  
class Geeks {
  
    // display method
    static void display(int str)
    {
          
        str = str + 5;
        Console.WriteLine(str);
    }
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating an List<T> of Integers
        List<int> firstlist = new List<int>();
  
        // Adding elements to List
        firstlist.Add(1);
        firstlist.Add(2);
        firstlist.Add(3);
        firstlist.Add(4);
        firstlist.Add(5);
        firstlist.Add(6);
        firstlist.Add(7);
  
        // using ForEach Method
        // which calls display method
        // on each element of the List
        firstlist.ForEach(display);
    }
}

Output:

6
7
8
9
10
11
12

Reference:


Article Tags :
C#