iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0

在程式開發中,經常需要處理「一堆資料」。
例如:要同時管理多檔股票,光靠一個一個變數會很難維護。
今天我們要學會 集合 (Collection),並透過 List<T>Dictionary<TKey, TValue> 來管理股票清單。


泛型 (Generic)

C# 的集合分成兩類:

  • 舊版非泛型集合,例如 ArrayList
  • 泛型集合,例如 List<T>

ArrayList 範例

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList list = new ArrayList();
        list.Add("2330");
        list.Add(1265m); // 可以放不同型別

        foreach (var item in list)
        {
            Console.WriteLine(item);
        }
    }
}

問題:

  • ArrayList 允許不同型別混在一起,容易出錯。
  • 取值時需要轉型,不安全。

List 範例

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> symbols = new List<string>();
        symbols.Add("2330");
        symbols.Add("2303");

        foreach (string s in symbols)
        {
            Console.WriteLine(s);
        }
    }
}

好處:

  • 型別安全(只能存放 string
  • 效能比 ArrayList 更好
  • 取值不用轉型

List 用法

List<T> 是動態陣列,可以隨時新增或移除元素。

List<string> stocks = new List<string>();
stocks.Add("2330");
stocks.Add("2303");

Console.WriteLine(stocks[0]);           // 2330
Console.WriteLine($"股票數量:{stocks.Count}");

常見操作:

  • Add() 新增
  • Remove() 移除
  • Count 取得數量
  • [] 透過索引存取

Dictionary 用法

Dictionary<TKey, TValue> 是「鍵值對集合」,適合快速查找。

Dictionary<string, decimal> prices = new Dictionary<string, decimal>();
prices["2330"] = 1265m;
prices["2303"] = 45.7m;

Console.WriteLine(prices["2330"]); // 1265

常見操作:

  • Add(key, value) 新增
  • ContainsKey(key) 判斷是否存在
  • Remove(key) 移除

使用時機

  • 用 List:需要「依序處理」的情境,例如輸出股票清單。
  • 用 Dictionary:需要「快速查找」的情境,例如輸入代號立即取得價格。

簡單記法:

  • List = 順序處理
  • Dictionary = 關鍵字查找

股票清單範例

public class Stock
{
    public string Symbol { get; set; }
    public decimal Price { get; set; }
}

class Program
{
    static void Main()
    {
        // 用 List 管理股票
        List<Stock> stocks = new List<Stock>
        {
            new Stock { Symbol = "2330", Price = 1265m },
            new Stock { Symbol = "2303", Price = 45.7m }
        };

        foreach (Stock s in stocks)
        {
            Console.WriteLine($"{s.Symbol} 價格 {s.Price}");
        }

        // 用 Dictionary 快速查找股票
        Dictionary<string, Stock> stockDict = new Dictionary<string, Stock>();
        stockDict["2330"] = new Stock { Symbol = "2330", Price = 1265m };

        if (stockDict.ContainsKey("2330"))
        {
            Console.WriteLine($"2330 的價格是 {stockDict["2330"].Price}");
        }
    }
}

小結

今天我們學會了:

  • 簡單介紹泛型語法
  • List<T> 適合依序處理資料
  • Dictionary<TKey, TValue> 適合快速查找資料
  • 股票清單管理:List 存清單,Dictionary 查價格

上一篇
Day 7 - 繼承、介面與 DI/IoC 初探
下一篇
Day 9 - LINQ 基礎:快速查詢資料
系列文
30天快速上手製作WPF選股工具 — 從C#基礎到LiteDB與Web API整合11
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言