Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để thực hiện một hành động cụ thể trên từng phần tử của Danh sách trong C #?

Để thực hiện một hành động cụ thể trên từng phần tử của Danh sách, mã như sau -

Ví dụ

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);
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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

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

Ví dụ

Bây giờ chúng ta hãy xem một ví dụ khác -

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);
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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

Updated List...
-25
0
25
50
150
200
225
250