CSharp · Console
/*
https://www.ptt.cc/bbs/C_Sharp/M.1618563753.A.310.html
*/
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
// 股票代號陣列
string[] stock_num = new string[] { "2330", "3008" };
// 陣列 轉為 List<Stock>
StockList stockList = new StockList(stock_num.Select(s => new Stock { Code = s }).ToList());
// 新增資料
stockList.AddStock(new Stock { Code = "0050", Name = "元大台灣50", Value = 139.25M, Qty = 3000 });
stockList.AddStock(new Stock { Code = "VTI", Name = "Vanguard Total Stock Market ETF", Value = 217.15M, Qty = 10 });
// 修改資料
stockList.EditStock(new Stock { Code = "2330", Name = "大立光", Value = 3140M, Qty = 10 });
stockList.EditStock(new Stock { Code = "3008", Name = "台積電", Value = 610M, Qty = 500 });
// 刪除資料
stockList.DeleteStock("VTI");
// 依代碼查詢單筆資料
Console.WriteLine(stockList.FindCodeOrDefault("2330"));
Console.WriteLine(stockList.FindCodeOrDefault("0056")); // 找不到會回傳 null
// 查詢所有資料
foreach (var stock in stockList.QueryAll())
{
Console.WriteLine(stock);
}
}
}
public class StockList
{
private List<Stock> _stockList = new List<Stock>();
public StockList(List<Stock> stockList)
{
if (stockList != null) _stockList = stockList;
}
public Stock FindCodeOrDefault(string code)
{
return _stockList.Find(f => f.Code == code);
}
public bool AddStock(Stock addStock)
{
if (FindCodeOrDefault(addStock.Code) != null) return EditStock(addStock);
_stockList.Add(addStock);
return true;
}
public bool EditStock(Stock editStock)
{
var stock = FindCodeOrDefault(editStock.Code);
if (stock == null) return false;
stock.Name = editStock.Name;
stock.Value = editStock.Value;
stock.Qty = editStock.Qty;
return true;
}
public bool DeleteStock(string code)
{
var deleteStock = _stockList.SingleOrDefault(s => s.Code == code);
_stockList.Remove(deleteStock);
return true;
}
public List<Stock> QueryAll()
{
return _stockList;
}
}
public class Stock
{
public string Code { get; set; }
public string Name { get; set; }
public decimal Value { get; set; }
public int Qty { get; set; }
public override string ToString()
{
return $"股票代號: {Code}、股票名稱: {Name}、股票價值: {Qty * Value}";
}
}