集合与常用类型

翻译整理自 Collections 与 Common Types。

1. 顺序集合

using System.Collections.Generic;

List<int> l = new() { 1, 2, 3 };
l.Add(4);
l.AddRange(new[] { 5, 6 });
l.Insert(0, 0);
l.Remove(3);
l.RemoveAt(0);
l.Contains(2);
l.IndexOf(2);
l.Count;
l.Clear();
l[0] = 99;

LinkedList<int> ll = new();
ll.AddLast(1); ll.AddFirst(0);

Queue<string> q = new();
q.Enqueue("a");
q.Dequeue();

Stack<int> s = new();
s.Push(1); s.Pop();

2. 关联集合

Dictionary<string, int> d = new()
{
    ["Alice"] = 90,
    ["Bob"] = 80
};

d["Carol"] = 85;
d.Remove("Bob");
d.ContainsKey("Alice");
d.TryGetValue("Alice", out var score);

foreach (var kv in d)
    Console.WriteLine($"{kv.Key}={kv.Value}");

SortedDictionary<string, int> sd = new();   // 按 key 排序
SortedSet<int> ss = new() { 3, 1, 2 };      // 有序集合

3. 不重复集合

HashSet<int> set = new() { 1, 2, 3 };
set.Add(1);            // 不会重复
set.Add(4);
set.Contains(2);
set.IntersectWith(new[] { 1, 2 });
set.UnionWith(new[] { 5, 6 });

var sub = set.IsSubsetOf(other);

4. 并发集合

using System.Collections.Concurrent;

ConcurrentDictionary<string, int> cd = new();
cd["x"] = 1;
cd.AddOrUpdate("x", 1, (k, v) => v + 1);

ConcurrentQueue<int> cq = new();
cq.Enqueue(1);

ConcurrentBag<int> cb = new();
cb.Add(1);

var ch = new BlockingCollection<int>(boundedCapacity: 10);

5. 不可变集合

using System.Collections.Immutable;

var list = ImmutableList.Create(1, 2, 3);
var list2 = list.Add(4);                       // 返回新实例,原不变

var dict = ImmutableDictionary.Create<string, int>();
var dict2 = dict.Add("x", 1);

var arr = ImmutableArray.Create(1, 2, 3);

6. Span 与 Memory

Span<int> span = new[] { 1, 2, 3, 4, 5 };
var slice = span.Slice(1, 2);                  // [2, 3]
span[0] = 99;

Memory<int> mem = new int[10];

ReadOnlySpan<char> ros = "hello";

Span 在栈上避免分配,性能关键路径必备。

7. 字符串处理

string s = "Hello, World";

s.Length;
s.Substring(0, 3);
s.IndexOf(",");
s.Contains("World");
s.Replace("World", "C#");
s.ToUpper();
s.Split(", ");
string.Join(", ", new[] { "a", "b" });
string.Concat("a", "b");
string.IsNullOrEmpty(s);
string.IsNullOrWhiteSpace("  ");

// 高效拼接
var sb = new StringBuilder();
for (int i = 0; i < 100; i++) sb.Append(i);
sb.ToString();

// 路径
Path.Combine("a", "b", "c.txt");
Path.GetFileName("a/b.txt");
Path.GetExtension("x.txt");

// 数值字符串
int.Parse("42");
int.TryParse("42", out var n);
42.ToString();
$"value={42,5}";

8. 日期时间

DateTime now = DateTime.Now;
DateTime utc = DateTime.UtcNow;
DateTime today = DateTime.Today;

TimeSpan ts = TimeSpan.FromHours(2);
DateTime future = now + ts;

DateOnly d = DateOnly.FromDateTime(now);
TimeOnly t = TimeOnly.FromDateTime(now);

DateTimeOffset dto = DateTimeOffset.Now;

TimeZoneInfo tz = TimeZoneInfo.Local;

9. TimeSpan 与 Stopwatch

var sw = Stopwatch.StartNew();
// ...
sw.Stop();
Console.WriteLine(sw.Elapsed);

10. 数值格式化

42.ToString("N0");              // 42
42.ToString("X");              // 2A
3.14159.ToString("F2");        // 3.14
$"{1234567:N0}";               // 1,234,567
$"{1234567:X8}";               // 0012D687

11. Tuple 与 ValueTuple

var t1 = Tuple.Create(1, "x");
var t2 = (1, "x");
(int, string) t3 = (1, "x");
var (n, s) = (1, "x");

小结

掌握集合、Span、字符串、日期后,已经能用 C# 应对绝大多数业务场景。