C# List ForEach

Description

List ForEach performs the specified action on each element of the List .

Syntax

List.ForEach has the following syntax.


public void ForEach(
  Action<T> action
)

Parameters

List.ForEach has the following parameters.

  • action - The Action delegate to perform on each element of the List.

Example

The following code uses Action<(Of <(T>)>) delegate to print the contents of a List<(Of <(T>)>) object.


using System;//w  w w  .  ja v a2  s. c  o  m
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<String> names = new List<String>();
        names.Add("A");
        names.Add("B");
        names.Add("C");
        names.Add("D");

        names.ForEach(Print);

        names.ForEach(delegate(String name)
        {
            Console.WriteLine(name);
        });
    }

    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}

The code above generates the following result.

Example 2

The following shows a compact Code for looping through the List with delegate.


using System;/*  w w w  .j  a  v a  2  s  .  c o m*/
using System.Collections.Generic;

class MainClass
{
    static void Main()
    {
        List<int> x = new List<int>();
        x.Add(5);
        x.Add(10);
        x.Add(15);
        x.Add(20);
        x.Add(25);

        x.ForEach(delegate(int n) { Console.WriteLine(Math.Sqrt(n)); }); 
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Collections.Generic »




HashSet
LinkedList
LinkedListNode
List
Queue
SortedSet
Stack