C# | How to perform a specified action on each element of the List
Last Updated :
01 Feb, 2019
List<T>.ForEach(Action<T>) Method is used to perform a specified action on each element of the List<T>.
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 the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
Syntax:
public void ForEach (Action action);
Parameter:
action: It is the Action<T> delegate to perform on each element of the List<T>.
Exceptions:
- ArgumentNullException: If the action is null.
- InvalidOperationException: If an element in the collection has been modified.
Below programs illustrate the use List<T>.ForEach(Action<T>) Method:
Example 1:
using System;
using System.Collections;
using System.Collections.Generic;
class Geeks {
static void display( string str)
{
Console.WriteLine(str);
}
public static void Main(String[] args)
{
List<String> firstlist = new List<String>();
firstlist.Add( "Geeks" );
firstlist.Add( "For" );
firstlist.Add( "Geeks" );
firstlist.Add( "GFG" );
firstlist.Add( "C#" );
firstlist.Add( "Tutorials" );
firstlist.Add( "GeeksforGeeks" );
firstlist.ForEach(display);
}
}
|
Output:
Geeks
For
Geeks
GFG
C#
Tutorials
GeeksforGeeks
Example 2:
using System;
using System.Collections;
using System.Collections.Generic;
class Geeks {
static void display( int str)
{
str = str + 5;
Console.WriteLine(str);
}
public static void Main(String[] args)
{
List< int > firstlist = new List< int >();
firstlist.Add(1);
firstlist.Add(2);
firstlist.Add(3);
firstlist.Add(4);
firstlist.Add(5);
firstlist.Add(6);
firstlist.Add(7);
firstlist.ForEach(display);
}
}
|
Output:
6
7
8
9
10
11
12
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...