Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Vòng lặp foreach trong C#

Khái niệm

foreach duyệt qua các phần tử của collection implement IEnumerable hoặc IEnumerable<T>. Cú pháp đơn giản, an toàn, không cần chỉ số.

Cú pháp

foreach (Type element in collection)
{
    // Xử lý element
}

Ví dụ: Duyệt LinkedList<int>

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        LinkedList list = new LinkedList();
        list.AddLast(25);
        list.AddLast(50);
        list.AddLast(100);
        list.AddLast(200);
        list.AddLast(400);
        list.AddLast(500);
        list.AddLast(550);
        list.AddLast(600);
        list.AddLast(800);
        list.AddLast(1200);

        Console.WriteLine($"Số node: {list.Count}");

        foreach (int val in list)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine($"\nCó node 800? {list.Contains(800)}");
    }
}

Kết quả

Số node: 10
25
50
100
200
400
500
550
600
800
1200

Có node 800? True

Đặc điểm quan trọng

  • **Read-only**: Không thể gán giá trị cho biến lặp (val = 10 lỗi compile).
  • Không thể sửa đổi collection trong khi duyệt (Add/Remove -> InvalidOperationException).
  • Sử dụng IEnumerator nội bộ: GetEnumerator(), MoveNext(), Current.
  • Hỗ trợ mảng, List, Dictionary, HashSet, Queue, Stack, v.v.

So sánh foreach vs for

Đặc điểmforeachfor
Cần indexKhôngCó
Sửa đổi collectionKhông (unsafe)Có (cẩn thận)
Hiệu năngTương đương (mảng), chút overhead (interface)Nhanh nhất cho mảng/List
Đọc codeSạch, rõ ý图Linh hoạt hơn

Foreach trên Dictionary

Dictionary dict = new() { {"A", 1}, {"B", 2} };

foreach (KeyValuePair kvp in dict)
{
    Console.WriteLine($"{kvp.Key} = {kvp.Value}");
}

// Hoặc deconstruct (C# 7+)
foreach (var (key, value) in dict)
{
    Console.WriteLine($"{key} = {value}");
}

Pattern Matching trong foreach (C# 9+)

object[] items = { 1, "hello", 3.14, null, 42 };

foreach (var item in items)
{
    Console.WriteLine(item switch
    {
        int i => $"Int: {i}",
        string s => $"String: {s}",
        double d => $"Double: {d}",
        null => "Null",
        _ => "Other"
    });
}