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

Duyệt List trong C#

Tạo List và thêm phần tử:

var products = new List<string>();
products.Add("Belts");
products.Add("T-Shirt");
products.Add("Trousers");

Duyệt bằng foreach:

foreach (var p in products)
    Console.WriteLine(p);

Ví dụ hoàn chỉnh

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(string[] args)
    {
        var products = new List<string>();
        products.Add("Belts");
        products.Add("T-Shirt");
        products.Add("Trousers");
        
        Console.WriteLine("Danh sách sản phẩm:");
        foreach (var p in products)
            Console.WriteLine(p);
    }
}

Các cách duyệt khác

  • for (int i = 0; i < list.Count; i++) - có index, có thể xóa khi duyệt
  • list.ForEach(item => Console.WriteLine(item)) - method List
  • list.Select((item, idx) => ...) - LINQ có index
  • foreach (var (item, idx) in list.Select((x,i) => (x,i))) - C# 7+ tuple

Lưu ý: Không sửa đổi list (Add/Remove) trong foreach -> InvalidOperationException. Dùng for lùi hoặc ToList() copy.