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

Cách khai báo và khởi tạo List trong C#

List<T> là danh sách động (dynamic array) kiểu mạnh trong System.Collections.Generic.

Các cách khởi tạo:

  1. Rỗng rồi Add:
    List<string> myList = new List<string>();
    myList.Add("one");
    myList.Add("two");
  2. Collection initializer (khuyến nghị):
    List<string> myList = new List<string> { "one", "two", "three" };
  3. Với capacity ban đầu:
    List<string> myList = new List<string>(100); // Tránh resize

Ví dụ

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> myList = new List<string> 
        { 
            "one", "two", "three", "four", "five", "size" 
        };
        Console.WriteLine(myList.Count); // 6
    }
}

Kết quả

6

Phương thức hay dùng: Add, AddRange, Insert, Remove, RemoveAt, Clear, Contains, Sort, Find, FindAll, ConvertAll.