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

Thêm phần tử vào List trong C#

Giới thiệu

List<T> (namespace System.Collections.Generic) là danh sách generic kiểu an toàn, phổ biến nhất. Phương thức Add(T item) thêm phần tử vào cuối danh sách. Cũng có AddRange, Insert, InsertRange.

Ví dụ 1: List với enumerator

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(string[] args)
    {
        List list = new List();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");
        list.Add("Four");
        list.Add("Five");
        list.Add("Six");
        list.Add("Seven");
        list.Add("Eight");

        Console.WriteLine("Enumerator duyệt qua các phần tử list...");
        List.Enumerator demoEnum = list.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }
    }
}

Kết quả

Enumerator duyệt qua các phần tử list...
One
Two
Three
Four
Five
Six
Seven
Eight

Ví dụ 2: List với enumerator

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(string[] args)
    {
        List list = new List();
        list.Add(50);
        list.Add(100);
        list.Add(150);
        list.Add(200);
        list.Add(250);
        list.Add(500);
        list.Add(750);
        list.Add(1000);
        list.Add(1250);
        list.Add(1500);

        Console.WriteLine("Enumerator duyệt qua các phần tử list...");
        List.Enumerator demoEnum = list.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            int res = demoEnum.Current;
            Console.WriteLine(res);
        }
    }
}

Kết quả

Enumerator duyệt qua các phần tử list...
50
100
150
200
250
500
750
1000
1250
1500

Mẹo

  • Dùng foreach đơn giản hơn enumerator thủ công.
  • Capacity có thể set trước qua constructor new List<T>(capacity) để tránh resize nhiều lần.
  • List<T> implement IList<T>, IReadOnlyList<T>, hỗ trợ LINQ.