2024-11-03 022-02_List_T泛型集合類別

2024-11-03 022-02_List_T泛型集合類別

好的,讓我們來深入了解 List<string> 是什麼型別,以及它在 C# 中的作用。之前的介紹中,我提到了許多內建的資料型別和參考型別,但確實沒有詳細介紹 泛型集合類別(Generic Collection Classes),其中就包括 List<T>。現在,我們將一步一步來解析 List<string> 的概念、特性以及如何使用它。


目錄

  1. List<T> 是什麼?
  2. List<string> 的型別解析
  3. List<T> 的優點
  4. 如何使用 List<T>
  5. 與陣列(Arrays)的比較
  6. 常見的方法與屬性
  7. 小結

1. List<T> 是什麼?

List<T> 是 C# 中一個非常常用的泛型集合類別,位於 System.Collections.Generic 命名空間下。它提供了一個動態大小的陣列,可以存儲任何類型的物件(由泛型參數 T 指定),並提供了豐富的方法來操作這些物件。

泛型(Generics) 允許你在定義類別、介面或方法時,指定一個或多個型別參數。這使得集合類別如 List<T> 能夠在保持類型安全的同時,靈活地處理不同的資料型別。


2. List<string> 的型別解析

當你使用 List<string> 時,實際上是在使用 List<T> 類別,並將泛型參數 T 指定為 string 型別。這意味著這個列表將專門用來存儲字串(string)類型的資料。

完整範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections.Generic;

class Program
{
static void Main(string[] args)
{
// 創建一個 List<string> 類型的變數
List<string> fruits = new List<string>();

// 添加元素到列表中
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");

// 遍歷並顯示列表中的元素
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}

輸出:

1
2
3
Apple
Banana
Cherry

解析:

  • List<string> fruits:這是一個 List 類別的實例,專門用來存儲 string 類型的資料。
  • new List<string>():創建一個新的 List<string> 物件。
  • fruits.Add("Apple"):向列表中添加一個元素。

3. List<T> 的優點

List<T> 相較於傳統的陣列(Arrays),具有許多優點:

  1. 動態大小:

    • 陣列的大小在宣告時必須固定,而 List<T> 可以根據需要動態地增加或減少元素數量。
  2. 豐富的方法:

    • List<T> 提供了許多方便的方法,如 AddRemoveInsertContainsFind 等,讓資料的操作更為簡便。
  3. 類型安全:

    • 由於使用泛型,List<T> 確保了列表中的所有元素都是相同的型別,避免了類型轉換錯誤。
  4. 性能優化:

    • List<T> 在內部使用陣列實現,並會自動處理陣列的擴展,因此在性能上比手動管理動態陣列更高效。

4. 如何使用 List<T>

讓我們通過一些具體的例子來了解如何使用 List<T>

a. 創建與初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Collections.Generic;

class Program
{
static void Main(string[] args)
{
// 創建一個空的 List<string>
List<string> cities = new List<string>();

// 使用初始化器創建並初始化 List<string>
List<string> countries = new List<string> { "USA", "Canada", "Mexico" };
}
}

b. 添加元素

1
2
3
cities.Add("New York");
cities.Add("Los Angeles");
cities.Add("Chicago");

c. 插入元素

1
2
// 在索引 1 處插入 "Houston"
cities.Insert(1, "Houston");

d. 移除元素

1
2
3
4
5
// 移除第一個出現的 "Chicago"
cities.Remove("Chicago");

// 根據索引移除元素
cities.RemoveAt(0); // 移除 "New York"

e. 訪問元素

1
2
string firstCity = cities[0];
Console.WriteLine(firstCity); // 輸出 "Houston"

f. 檢查是否包含某個元素

1
2
bool hasLA = cities.Contains("Los Angeles");
Console.WriteLine(hasLA); // 輸出 True

g. 獲取列表的大小

1
2
int count = cities.Count;
Console.WriteLine(count); // 輸出列表中元素的數量

5. 與陣列(Arrays)的比較

特性 陣列(Array) List<T>
大小 固定,宣告時指定大小 動態,能自動擴展或縮減
方法支持 基本的方法,如索引訪問 豐富的方法,如 AddRemove
類型安全 是,尤其是使用泛型陣列 是,使用泛型確保元素類型一致
性能 高效,適合固定大小的資料 略低於陣列,但提供更多靈活性
使用情境 資料大小已知且不變 需要動態管理資料集合時

範例:

1
2
3
4
5
6
// 使用陣列
string[] arrayCities = new string[3] { "Paris", "Berlin", "Tokyo" };

// 使用 List<string>
List<string> listCities = new List<string> { "Paris", "Berlin", "Tokyo" };
listCities.Add("Sydney"); // 動態添加

6. 常見的方法與屬性

以下是 List<T> 中一些常用的方法和屬性:

  • 添加元素:

    • Add(T item):在列表末尾添加一個元素。
    • AddRange(IEnumerable<T> collection):添加一個集合中的所有元素。
  • 移除元素:

    • Remove(T item):移除第一個匹配的元素。
    • RemoveAt(int index):根據索引移除元素。
    • Clear():清空列表中的所有元素。
  • 查詢與搜尋:

    • Contains(T item):檢查列表中是否包含指定元素。
    • IndexOf(T item):獲取元素的索引。
    • Find(Predicate<T> match):找到第一個符合條件的元素。
    • FindAll(Predicate<T> match):找到所有符合條件的元素。
  • 排序與反轉:

    • Sort():對列表中的元素進行排序。
    • Reverse():反轉列表中元素的順序。
  • 轉換與複製:

    • ToArray():將列表轉換為陣列。
    • CopyTo(T[] array, int arrayIndex):將元素複製到指定的陣列中。

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Collections.Generic;

class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 5, 3, 8, 1, 2 };

// 添加元素
numbers.Add(10);

// 移除元素
numbers.Remove(3); // 移除值為 3 的元素
numbers.RemoveAt(0); // 移除索引 0 的元素

// 查詢
bool hasEight = numbers.Contains(8); // 返回 true
int index = numbers.IndexOf(8); // 返回 1

// 找到第一個大於 5 的數字
int firstGreaterThanFive = numbers.Find(x => x > 5);

// 排序
numbers.Sort();

// 反轉
numbers.Reverse();

// 輸出結果
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}

輸出:

1
2
3
10
8
2

7. 小結

  • List<T> 是什麼:

    • 一個泛型集合類別,允許存儲任意型別的物件,並提供豐富的方法來管理這些物件。
  • List<string> 的特性:

    • 專門用來存儲 string 類型的資料。
    • 支持動態增減元素,類型安全,並提供各種便捷的方法來操作列表。
  • 與陣列的比較:

    • List<T> 更加靈活,適用於需要頻繁增減元素的情境,而陣列則適合大小固定且性能要求較高的場合。
  • 常用方法與屬性:

    • AddRemoveFindSort 等方法使得 List<T> 在處理資料集合時非常方便。

了解並善用 List<T>,可以讓你在 C# 中更高效地處理各種資料集合需求。如果你有更多關於 List<T> 或其他 C# 集合類別的問題,請隨時告訴我!