首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 常用函式與方法速查手冊:DateTime、字串、編碼、集合、LINQ

     編輯:關於C語言

DateTime 與時間處理

取得當下時間

DateTime now = DateTime.Now;           // 本地時間
DateTime utc = DateTime.UtcNow;        // UTC 時間 (推薦儲存/傳輸用)
DateTime today = DateTime.Today;       // 今日 00:00:00

元件存取

int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;
int ms = now.Millisecond;
DayOfWeek dow = now.DayOfWeek;         // 週幾
int doy = now.DayOfYear;               // 第幾天

格式化輸出 (ToString 格式字串)

格式說明範例輸出
yyyy-MM-dd標準日期2024-03-15
HH:mm:ss24小時制時間14:30:05
yyyy-MM-dd HH:mm:ss完整日期時間2024-03-15 14:30:05
yyyy/MM/dd斜線分隔2024/03/15
D長日期格式 (文化特性)2024年3月15日
T長時間格式下午 02:30:05
f完整日期時間 (短時間)2024年3月15日 下午 02:30
o / sISO 8601 / 可排序2024-03-15T14:30:05.1234567
rRFC 1123 (HTTP 標頭)Fri, 15 Mar 2024 06:30:05 GMT

日期運算

DateTime future = now.AddDays(30);
DateTime past = now.AddMonths(-3);
DateTime specific = new DateTime(2024, 12, 25);
TimeSpan diff = future - now;          // 差值
double totalHours = diff.TotalHours;
int days = diff.Days;

// 週期運算
DateTime firstDayOfMonth = new DateTime(now.Year, now.Month, 1);
DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

解析字串

DateTime parsed = DateTime.Parse("2024-03-15");           // 依目前文化特性
DateTime parsed2 = DateTime.ParseExact("15/03/2024", "dd/MM/yyyy", CultureInfo.InvariantCulture);
bool success = DateTime.TryParse(input, out DateTime result); // 安全解析

字串操作核心大全

建立與連接


// 字串插值 (C# 6+, 效能佳、可讀)
string s = $"User: {name}, Age: {age}, Time: {DateTime.Now:HH:mm}";

// StringBuilder (大量連接/迴圈中)
var sb = new StringBuilder();
for (int i = 0; i < 100; i++) sb.AppendLine($"Line {i}");
string result = sb.ToString();

// string.Join (陣列/集合連接)
string csv = string.Join(",", new[] { "A", "B", "C" }); // "A,B,C"

查找與比較


string text = "Hello World";

// 索引查找
int idx = text.IndexOf("World");     // 6 (找不到回傳 -1)
int last = text.LastIndexOf("l");    // 9
bool starts = text.StartsWith("He"); // true
bool ends = text.EndsWith("ld");     // true
bool contains = text.Contains("lo"); // true

// 比較 (忽略大小寫)
bool eq = text.Equals("hello world", StringComparison.OrdinalIgnoreCase);
bool eq2 = string.Equals(text, "HELLO WORLD", StringComparison.OrdinalIgnoreCase);

// 排序比較
int cmp = string.Compare("A", "B", StringComparison.Ordinal); // -1

擷取與移除


string s = "Hello World";

string sub = s.Substring(6);       // "World" (從索引 6 到結尾)
string sub2 = s.Substring(6, 3);   // "Wor" (長度 3)

// 移除
string removed = s.Remove(5);      // "Hello" (索引 5 之後刪除)
string removed2 = s.Remove(5, 6);  // "Hello" (索引 5 刪除 6 字元)

// 取代
string replaced = s.Replace("World", "C#"); // "Hello C#"
string multi = s.Replace("l", "L");         // "HeLLo WorLd" (全部取代)

分割與修剪


string csv = "A,B,C, D ,E";
string[] parts = csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
// 結果: ["A", "B", "C", "D", "E"]

string padded = "  Hello  ";
string trimmed = padded.Trim();       // "Hello"
string trimStart = padded.TrimStart(); // "Hello  "
string trimEnd = padded.TrimEnd();     // "  Hello"

格式化數值/日期


int num = 12345;
num.ToString("N");    // "12,345.00" (千分位)
num.ToString("C");    // "NT$12,345.00" (貨幣)
num.ToString("X");    // "3039" (十六進位)
num.ToString("D8");   // "00012345" (補零)

double d = 0.1234;
d.ToString("P");      // "12.34%" (百分比)
d.ToString("E");      // "1.234000E-001" (科學記號)

編碼轉換


string text = "中文";
byte[] utf8 = Encoding.UTF8.GetBytes(text);
byte[] unicode = Encoding.Unicode.GetBytes(text);     // UTF-16 LE
byte[] bigEndian = Encoding.BigEndianUnicode.GetBytes(text);

string back = Encoding.UTF8.GetString(utf8); // 還原

// Base64
string b64 = Convert.ToBase64String(utf8);
byte[] decoded = Convert.FromBase64String(b64);

集合與 LINQ 必備技巧

List<T> 常用操作


var list = new List { 3, 1, 4, 1, 5 };

list.Add(9);
list.AddRange(new[] { 2, 6 });
list.Insert(0, 0);           // 索引 0 插入
list.Remove(1);              // 移除第一個 1
list.RemoveAt(0);            // 移除索引 0
list.RemoveAll(x => x > 5);  // 移除所有 > 5
list.Sort();                 // 就地排序
list.Reverse();              // 反轉
bool has = list.Contains(3);
int idx = list.IndexOf(4);
int count = list.Count;
int[] arr = list.ToArray();

Dictionary<TKey, TValue>


var dict = new Dictionary
{
    ["Apple"] = 1,
    ["Banana"] = 2
};

dict["Cherry"] = 3;          // 新增/更新
bool exists = dict.TryGetValue("Apple", out int val); // 安全取值
dict.Remove("Banana");
foreach (var kvp in dict) { /* kvp.Key, kvp.Value */ }
var keys = dict.Keys;
var values = dict.Values;

LINQ 核心查詢語法 (方法語法)


var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// 篩選
var evens = numbers.Where(n => n % 2 == 0);           // 2,4,6,8,10

// 投影
var squares = numbers.Select(n => n * n);             // 1,4,9,16,25

// 排序
var desc = numbers.OrderByDescending(n => n);         // 10..1

// 分組
var grouped = numbers.GroupBy(n => n % 2);            // 兩群:奇/偶

// 聚合
int sum = numbers.Sum();
double avg = numbers.Average();
int max = numbers.Max();
int min = numbers.Min();

// 取前幾筆 / 跳過
var top3 = numbers.Take(3);                           // 1,2,3
var skip2 = numbers.Skip(2);                          // 3..10

// 判斷
bool any = numbers.Any(n => n > 5);                   // true
bool all = numbers.All(n => n > 0);                   // true

// 轉換
List list = numbers.ToList();
Dictionary dict = numbers.ToDictionary(n => n, n => n * 10);
HashSet set = numbers.ToHashSet();

// 連接 (Join)
var users = new[] { new { Id = 1, Name = "A" }, new { Id = 2, Name = "B" } };
var orders = new[] { new { UserId = 1, Amount = 100 }, new { UserId = 1, Amount = 200 } };
var q = users.Join(orders, u => u.Id, o => o.UserId, (u, o) => new { u.Name, o.Amount });

LINQ 查詢語法 (SQL 風格)


var result = from n in numbers
             where n % 2 == 0
             orderby n descending
             select n * n;
// 編譯器轉換為方法語法,效能相同

常用類別靜態方法速查

類別方法用途
PathCombine, GetFileName, GetExtension, GetDirectoryName, GetTempFileName路徑操作 (跨平台安全)
FileReadAllText, WriteAllText, ReadAllLines, Exists, Copy, Move, Delete檔案整體讀寫
DirectoryCreateDirectory, Exists, GetFiles, GetDirectories, Delete目錄操作
EnvironmentGetFolderPath, GetEnvironmentVariable, MachineName, ProcessorCount, TickCount系統環境資訊
GuidNewGuid(), Parse(), TryParse()唯一識別碼
ConvertToBase64String, FromBase64String, ToInt32, ChangeType型別轉換、編碼
MathMax, Min, Abs, Round, Ceiling, Floor, Pow, Sqrt, Random數學運算
RegexIsMatch, Match, Matches, Replace, Split正則表達式

結語

熟練掌握上述 API,能解決 90% 以上的日常開發需求。建議:

  1. 優先使用 LINQ 表達資料轉換邏輯,減少手寫迴圈
  2. 字串大量操作用 StringBuilder,單行插值用 $""
  3. 日期儲存用 UTC,顯示時轉本地時區
  4. 編碼統一用 UTF-8,避免 BigEndianUnicode 除非協定要求
  5. 善用 Try 系列方法 (TryParse, TryGetValue) 避免例外控制流程
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved