文章

第12天:集合與陣列

課程簡介

今天,我們將學習 C# 中的 集合(Collections)和 陣列(Arrays)。陣列是存儲固定大小的同類型資料的容器,而集合則是更強大且靈活的資料結構,能夠存儲動態數量的元素。C# 提供了許多集合類別,例如 ListDictionaryQueue,每種集合有不同的使用場景和特點。


學習目標

  • 瞭解陣列的基本概念與操作
  • 瞭解集合的概念及其類型
  • 學習使用 ListDictionary 等集合類別
  • 理解集合和陣列的異同

課程內容

1. 陣列(Array)

陣列 是一組固定大小且類型相同的元素的集合。使用陣列可以將多個元素儲存在一個變數中,並根據索引來存取特定元素。陣列的大小在創建時必須確定,且無法更改。

陣列的特點

  • 可以存放固定數量的元素
  • 索引從 0 開始
  • 資料類型必須一致

範例:

1
2
3
4
5
int[] numbers = new int[5] {1, 2, 3, 4, 5};
Console.WriteLine(numbers[0]);  // 輸出 1

string[] fruits = {"Apple", "Banana", "Cherry"};
Console.WriteLine(fruits[1]);  // 輸出 "Banana"

操作方法

  • 初始化:使用 new 關鍵字分配陣列大小。
  • 存取元素:使用索引(例如 numbers[0])來存取元素。
  • 迭代元素:可以使用 forforeach 迴圈遍歷陣列元素。

2. 集合(Collections)

集合是一組具有特定資料結構的元素集合,可以動態擴展和縮小。與陣列不同,集合的大小不固定,可以根據需求添加或刪除元素。C# 提供了多種集合類別,每個集合類別都具備不同的特性和用途。

常見集合類型

  • List:一種動態大小的集合,可以存放相同類型的資料,並支援索引存取。
  • Dictionary:一種鍵值對(key-value pair)的集合,透過鍵來快速查找值。
  • Queue:先進先出(FIFO)的集合,元素從尾端加入,從頭部取出。
  • Stack:後進先出(LIFO)的集合,元素從尾端加入,從尾端取出。

3. 使用 List

List 是 C# 中最常用的集合類型之一,可以存放相同類型的元素且動態調整大小。

List 的基本操作

  • 新增元素:使用 .Add() 方法
  • 插入元素:使用 .Insert() 方法
  • 刪除元素:使用 .Remove().RemoveAt() 方法
  • 存取元素:使用索引 []

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
List<string> cities = new List<string>();
cities.Add("Tokyo");
cities.Add("New York");
cities.Add("London");

Console.WriteLine(cities[1]);  // 輸出 "New York"

cities.Insert(1, "Paris");
cities.Remove("Tokyo");

foreach (string city in cities)
{
    Console.WriteLine(city);
}

此範例中,List 的大小可以動態變化,能夠新增或刪除元素。您也可以用 foreach 迴圈遍歷 List 中的所有元素。


4. 使用 Dictionary

Dictionary 是一種以鍵值對(key-value pair)形式存儲資料的集合。可以快速透過鍵來存取對應的值。

Dictionary 的基本操作

  • 新增鍵值對:使用 .Add() 方法
  • 刪除鍵值對:使用 .Remove() 方法
  • 查找值:使用鍵 []
  • 檢查鍵是否存在:使用 .ContainsKey() 方法

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 25);
ages.Add("Bob", 30);
ages["Charlie"] = 35;

Console.WriteLine(ages["Bob"]);  // 輸出 30

if (ages.ContainsKey("Alice"))
{
    Console.WriteLine("Alice is " + ages["Alice"] + " years old.");
}

ages.Remove("Charlie");

在此範例中,您可以透過鍵(例如 "Alice")快速存取對應的值。Dictionary 中的鍵必須是唯一的,不能有重複鍵。


5. 集合與陣列的異同

特性陣列(Array)集合(Collection)
大小固定動態
資料類型相同類型相同類型(泛型)或不同類型
操作方法索引存取多種操作方法(新增、刪除、查找)
使用情境預先知道大小且不變時適用大小不定或需要動態調整時適用

實作練習

  1. 使用陣列存儲學生分數
    • Program.cs 中撰寫程式碼,使用陣列存儲 5 個學生的分數,並計算平均分數。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    using System;
    
    class Program
    {
        static void Main(string[] args)
        {
            int[] scores = {85, 92, 78, 90, 88};
            int sum = 0;
    
            for (int i = 0; i < scores.Length; i++)
            {
                sum += scores[i];
            }
    
            double average = (double)sum / scores.Length;
            Console.WriteLine("Average score: " + average);
        }
    }
    
  2. 使用 List 存儲購物清單
    • 撰寫程式碼,允許使用者輸入購物清單項目,並顯示所有項目。
    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
    
    using System;
    using System.Collections.Generic;
    
    class Program
    {
        static void Main(string[] args)
        {
            List<string> shoppingList = new List<string>();
            Console.WriteLine("Enter items for your shopping list (type 'done' to finish):");
    
            while (true)
            {
                string item = Console.ReadLine();
                if (item.ToLower() == "done")
                    break;
                shoppingList.Add(item);
            }
    
            Console.WriteLine("Your Shopping List:");
            foreach (string item in shoppingList)
            {
                Console.WriteLine("- " + item);
            }
        }
    }
    
  3. 使用 Dictionary 存儲聯絡人名單
    • 撰寫程式碼,使用 Dictionary 儲存聯絡人姓名及其電話號碼,並能查找特定聯絡人。
    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
    
    using System;
    using System.Collections.Generic;
    
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> contacts = new Dictionary<string, string>();
            contacts.Add("Alice", "123-456-7890");
            contacts.Add("Bob", "987-654-3210");
            contacts["Charlie"] = "555-123-4567";
    
            Console.WriteLine("Enter a name to find the contact number:");
            string name = Console.ReadLine();
    
            if (contacts.ContainsKey(name))
            {
                Console.WriteLine(name + "'s number is " + contacts[name]);
            }
            else
            {
                Console.WriteLine("Contact not found.");
            }
        }
    }
    

教學重點

  • 瞭解陣列和集合的基本特點及其使用情境。
  • 探索 ListDictionary 的常用操作方法。
  • 使用不同集合類別,根據需求選擇適當的資料結構來管理和操作數據。

在下一節中,我們將學習如何使用 Lambda 表達式和 LINQ 來高效操作集合資料。

本文章以 CC BY 4.0 授權