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

CsharpServer Side ProgrammingProgramming

To perform a specified action on each element of the List, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void demo(int s){
      s = s * 10;
      Console.WriteLine(s);
   }
   public static void Main(String[] args){
      List<int> list = new List<int>();
      list.Add(25);
      list.Add(50);
      list.Add(75);
      list.Add(100);
      list.Add(200);
      list.Add(250);
      list.Add(275);
      list.Add(300);
      Console.WriteLine("List...");
      foreach (int i in list){
         Console.WriteLine(i);
      }
      Console.WriteLine("\nUpdated List...");
      list.ForEach(demo);
   }
}

Output

This will produce the following output −

List...
25
50
75
100
200
250
275
300

Updated List...
250
500
750
1000
2000
2500
2750
3000

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void demo(int s){
      s = s - 50;
      Console.WriteLine(s);
   }
   public static void Main(String[] args){
      List<int> list = new List<int>();
      list.Add(25);
      list.Add(50);
      list.Add(75);
      list.Add(100);
      list.Add(200);
      list.Add(250);
      list.Add(275);
      list.Add(300);
      Console.WriteLine("List...");
      foreach (int i in list){
         Console.WriteLine(i);
      }
      Console.WriteLine("\nUpdated List...");
      list.ForEach(demo);
   }
}

Output

This will produce the following output −

List...
25
50
75
100
200
250
275
300

Updated List...
-25
0
25
50
150
200
225
250
raja
Published on 11-Dec-2019 05:01:44
Advertisements