C# 集合

15.1 List

创建与初始化

1
2
3
4
5
6
7
8
// 创建空列表
List<int> numbers = new();

// 初始化
List<string> fruits = new() { "apple", "banana", "orange" };

// 指定容量
List<int> scores = new(100);

常用操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
List<string> fruits = new();

// 添加
fruits.Add("apple");
fruits.AddRange(new[] { "banana", "orange" });

// 插入
fruits.Insert(1, "grape");

// 访问
Console.WriteLine(fruits[0]); // apple

// 修改
fruits[0] = "Apple";

// 删除
fruits.Remove("banana");
fruits.RemoveAt(0);
fruits.RemoveAll(f => f.StartsWith("o"));

// 查找
bool has = fruits.Contains("apple");
int index = fruits.IndexOf("orange");
string found = fruits.Find(f => f.Length > 5);

// 排序
fruits.Sort();
fruits.Reverse();

// 数量
Console.WriteLine(fruits.Count);

15.2 Dictionary<TKey, TValue>

创建与初始化

1
2
3
4
5
6
7
8
9
10
// 创建字典
Dictionary<string, int> ages = new();

// 初始化
var scores = new Dictionary<string, int>
{
{ "Alice", 85 },
{ "Bob", 90 },
{ "Charlie", 78 }
};

常用操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var dict = new Dictionary<string, int>();

// 添加
dict.Add("Alice", 25);
dict["Bob"] = 30; // 添加或更新

// 访问
Console.WriteLine(dict["Alice"]); // 25

// 安全访问
if (dict.TryGetValue("Charlie", out int age))
{
Console.WriteLine(age);
}

// 检查
bool has = dict.ContainsKey("Alice");
bool hasVal = dict.ContainsValue(25);

// 删除
dict.Remove("Bob");

// 遍历
foreach (var kvp in dict)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

foreach (var key in dict.Keys)
{
Console.WriteLine(key);
}

15.3 Queue 与 Stack

Queue 队列(FIFO)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Queue<string> queue = new();

// 入队
queue.Enqueue("first");
queue.Enqueue("second");
queue.Enqueue("third");

// 查看
Console.WriteLine(queue.Peek()); // first

// 出队
string first = queue.Dequeue(); // first

// 数量
Console.WriteLine(queue.Count); // 2

Stack 栈(LIFO)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Stack<string> stack = new();

// 入栈
stack.Push("first");
stack.Push("second");
stack.Push("third");

// 查看
Console.WriteLine(stack.Peek()); // third

// 出栈
string top = stack.Pop(); // third

// 数量
Console.WriteLine(stack.Count); // 2

15.4 HashSet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
HashSet<int> numbers = new();

// 添加
numbers.Add(1);
numbers.Add(2);
numbers.Add(2); // 重复,不添加

// 检查
Console.WriteLine(numbers.Contains(1)); // True

// 集合运算
HashSet<int> set1 = new() { 1, 2, 3, 4 };
HashSet<int> set2 = new() { 3, 4, 5, 6 };

set1.UnionWith(set2); // 并集: 1,2,3,4,5,6
set1.IntersectWith(set2); // 交集: 3,4,5,6
set1.ExceptWith(set2); // 差集: 1,2
set1.SymmetricExceptWith(set2); // 对称差集

15.5 LINQ 基础

查询语法

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

var query = from n in numbers
where n > 3
orderby n
select n;

foreach (var n in query)
{
Console.WriteLine(n); // 5, 8, 9
}

方法语法

1
2
3
4
var result = numbers
.Where(n => n > 3)
.OrderBy(n => n)
.ToList();

常用操作符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int[] numbers = { 5, 2, 8, 1, 9, 3 };

// 过滤
var filtered = numbers.Where(n => n > 3);

// 投影
var squares = numbers.Select(n => n * n);

// 排序
var sorted = numbers.OrderBy(n => n);
var desc = numbers.OrderByDescending(n => n);

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

// 分页
var page = numbers.Skip(2).Take(3); // 跳过 2 个,取 3 个

// 转换
List<int> list = numbers.ToList();
int[] array = numbers.ToArray();
Dictionary<int, string> dict = numbers.ToDictionary(n => n, n => $"Item{n}");

15.6 集合选择指南

场景 推荐集合
有序列表 List<T>
键值对 Dictionary<K,V>
先进先出 Queue<T>
后进先出 Stack<T>
去重 HashSet<T>
线程安全 ConcurrentDictionary<K,V>

15.7 本章小结

  • List<T> 是最常用的动态数组
  • Dictionary<K,V> 提供键值对存储
  • Queue<T> 先进先出,Stack<T> 后进先出
  • HashSet<T> 用于去重和集合运算
  • LINQ 提供强大的查询功能
  • 根据场景选择合适的集合类型

练习题

  1. 使用 List<T> 存储学生成绩,计算平均分
  2. 使用 Dictionary 统计单词出现频率
  3. 使用 LINQ 过滤并排序集合
  4. 以下代码输出什么?
    1
    2
    3
    var dict = new Dictionary<string, int> { {"A", 1} };
    dict["A"] = 2;
    Console.WriteLine(dict["A"]);
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
C#基础教程 系列
第 15/20 篇
分享: