iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0

在管理股票清單時,我們常常需要「篩選」、「轉換」、「排序」資料。
C# 提供了 LINQ (Language Integrated Query),可以用直覺的方式來查詢集合資料。


LINQ 語法簡介

LINQ 主要有兩種寫法:

  • 方法語法 (Method Syntax)stocks.Where(x => x.Code == "2330")
  • 查詢語法 (Query Syntax)from s in stocks where s.Code == "2330" select s

初學時建議用方法語法,比較直觀。


建立假資料

我們先準備一份股票清單(至少 10 筆)。

定義DTO:

using LiteDB;

namespace TwStockMaster.Utils.Models
{
    /// <summary>
    /// Stock profile master record for Taiwan securities and indices.
    /// 台灣證券與指數的主檔資料。
    /// </summary>
    public sealed class StockProfile
    {
        // LiteDB
        [BsonId]
        public string Code { get; set; } = default!;

        /// <summary>
        /// Localized display name.
        /// 中文名稱。
        /// </summary>
        public string Name { get; set; } = default!;

        /// <summary>
        /// Market board code (default TSE).
        /// 市場板別代碼(預設為上市)。
        /// </summary>
        public MarketCode Market { get; set; } = MarketCode.TSE;

        /// <summary>
        /// Country code (default TW).
        /// 國家代碼(預設為台灣)。
        /// </summary>
        public Country Country { get; set; } = Country.TW;

        /// <summary>
        /// Industry/sector mapping if applicable.
        /// 產業別(如屬於某產業或子產業)。
        /// </summary>
        public string? Industry { get; set; }

        /// <summary>
        /// Board/Category tags (optional, e.g., ETF/ETN/ESG).
        /// 類別標籤(選用,例如 ETF/ETN/ESG)。
        /// </summary>
        public string[]? Tags { get; set; }

        /// <summary>
        /// Last time the profile was refreshed (UTC).
        /// 主檔最後更新時間(UTC)。
        /// </summary>
        public DateTime LastUpdatedUtc { get; set; }
    }
}

範例:

using System;
using System.Collections.Generic;
using System.Linq;
using TwStockMaster.Utils.Models;

class Program
{
    static void Main()
    {
        List<StockProfile> stocks = new List<StockProfile>
        {
            new StockProfile { Code = "2330", Name = "台積電", Industry = "半導體", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2303", Name = "聯電", Industry = "半導體", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2317", Name = "鴻海", Industry = "電子代工", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2881", Name = "富邦金", Industry = "金融", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2882", Name = "國泰金", Industry = "金融", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "1216", Name = "統一", Industry = "食品", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "1301", Name = "台塑", Industry = "塑膠", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2002", Name = "中鋼", Industry = "鋼鐵", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2610", Name = "華航", Industry = "航運", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2603", Name = "長榮", Industry = "航運", LastUpdatedUtc = DateTime.UtcNow },
        };
    }
}

Where 範例:篩選股價條件

假設我們有個需求:找到「金融產業」的股票。

var financeStocks = stocks.Where(s => s.Industry == "金融");

foreach (var stock in financeStocks)
{
    Console.WriteLine($"{stock.Code} {stock.Name}");
}

輸出:

2881 富邦金
2882 國泰金

Select 範例:投影新資料

有時候只想要股票代號與名稱,不需要完整物件。

var simpleList = stocks.Select(s => new { s.Code, s.Name });

foreach (var item in simpleList)
{
    Console.WriteLine($"{item.Code} {item.Name}");
}

輸出:

2330 台積電
2303 聯電
2317 鴻海
...

OrderBy 範例:排序

假設我們想依照 代號排序

var ordered = stocks.OrderBy(s => s.Code);

foreach (var s in ordered)
{
    Console.WriteLine($"{s.Code} {s.Name}");
}

輸出(部分):

1216 統一
1301 台塑
2002 中鋼
2303 聯電
2330 台積電
...

實戰範例:篩選半導體產業股票,取出代號與名稱,並依照代號排序

using System;
using System.Collections.Generic;
using System.Linq;
using TwStockMaster.Utils.Models;

class Program
{
    static void Main()
    {
        List<StockProfile> stocks = new List<StockProfile>
        {
            new StockProfile { Code = "2330", Name = "台積電", Industry = "半導體", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2303", Name = "聯電", Industry = "半導體", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2317", Name = "鴻海", Industry = "電子代工", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2881", Name = "富邦金", Industry = "金融", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "1301", Name = "台塑", Industry = "塑膠", LastUpdatedUtc = DateTime.UtcNow },
            new StockProfile { Code = "2002", Name = "中鋼", Industry = "鋼鐵", LastUpdatedUtc = DateTime.UtcNow },
        };

        var query = stocks
            .Where(s => s.Industry == "半導體")           // 篩選產業
            .OrderBy(s => s.Code)                         // 依代號排序
            .Select(s => new { s.Code, s.Name });         // 投影出需要的欄位

        foreach (var item in query)
        {
            Console.WriteLine($"{item.Code} {item.Name}");
        }
    }
}

執行結果

2303 聯電
2330 台積電

這樣的範例一次示範了 Where → OrderBy → Select 的流程。

小結

今天我們學會了:

  • LINQ 的基本語法
  • Where:篩選資料
  • Select:投影資料
  • OrderBy:排序資料
  • 用假資料模擬股票清單,快速查詢所需資訊


上一篇
Day 8 - 集合 (List, Dictionary) 與股票清單管理
下一篇
Day 10 - 例外處理 (Exception Handling)
系列文
30天快速上手製作WPF選股工具 — 從C#基礎到LiteDB與Web API整合11
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言