集合类型

集合类型(Collections)

集合是比数组更灵活的动态数据结构,C# 中最常用的是 System.Collections.Generic 命名空间下的类型。

List<T>(动态数组)

List<int> list = new List<int> { 1, 2, 3 };
list.Add(4);           // 追加
list.Insert(0, 0);     // 插入
list.Remove(2);        // 删除元素
list.RemoveAt(0);      // 按下标删除
list.Contains(3);      // 是否包含
list.Count             // 数量

Dictionary<K,V>(键值对)

Dictionary<string, int> dict = new();
dict["apple"] = 3;
dict.TryGetValue("apple", out int v);
foreach (var kv in dict) { }

HashSet<T>(集合,去重)

HashSet<int> set = new() { 1, 2, 3 };
set.Add(3);      // 已存在,返回 false

Queue<T> / Stack<T>

Queue<int> q = new(); q.Enqueue(1); q.Dequeue();
Stack<int> s = new(); s.Push(1); s.Pop();

LINQ 扩展

list.Where(x => x > 2).OrderBy(x => x).ToList();

“您的支持是我持续分享的动力”

微信收款码
微信
支付宝收款码
支付宝

目录