Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีดำเนินการเฉพาะเจาะจงกับแต่ละสมาชิกของ List ใน C#

ภาพรวม

เมธอด List<T>.ForEach(Action<T>) ทำการกระทำ (delegate) กับทุกสมาชิกใน List ตามลำดับ

ตัวอย่าง 1: คูณ 10

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 list = new List();
        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);
    }
}

ผลลัพธ์ตัวอย่าง 1

List...
25
50
75
100
200
250
275
300
Updated List...
250
500
750
1000
2000
2500
2750
3000

ตัวอย่าง 2: ลบ 50

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 list = new List();
        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);
    }
}

ผลลัพธ์ตัวอย่าง 2

List...
25
50
75
100
200
250
275
300
Updated List...
-25
0
25
50
150
200
225
250

สรุป

  • ForEach รับ delegate/lambda Action<T>
  • ไม่เปลี่ยนค่าใน List โดยตรง (parameter passed by value)
  • ใช้สำหรับ side-effect เช่นพิมพ์, เขียนไฟล์, ส่งข้อมูล