keywords: 集合, List, Dictionary, HashSet, C#, 数据结构


集合是编程中常用的数据结构之一,用于存储和管理一组数据。在 C# 中,集合类提供了丰富的功能,使得数据的存取和操作更加便捷高效。本章将详细介绍 List、Dictionary 和 HashSet 以及它们的常用操作。

什么是集合

集合是一种数据结构,用于存储一组相关的数据项。与数组不同,集合提供了更强大的功能,如动态大小调整、复杂查询和数据操作。在 C# 中,集合类都位于 System.Collections.Generic 命名空间下,主要包括以下几种:

  • List: 一种动态数组,能够按索引快速访问元素。
  • Dictionary: 一种键值对集合,能够通过键快速查找值。
  • HashSet: 一种无序集合,不允许包含重复元素。

List

定义和初始化

List<T> 是一种常用的泛型集合,提供了动态大小调整和高效的元素访问。以下是 List<T> 的定义和初始化方法:

  1. using System;
  2. using System.Collections.Generic;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. // 定义和初始化
  8. List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
  9. // 添加元素
  10. names.Add("Dave");
  11. // 访问元素
  12. Console.WriteLine(names[2]); // 输出:Charlie
  13. // 遍历集合
  14. foreach (var name in names)
  15. {
  16. Console.WriteLine(name);
  17. }
  18. }
  19. }

常用操作

下面是一些 List<T> 的常用操作:

  • 添加元素: 使用 Add 方法添加单个元素,使用 AddRange 方法添加多个元素。
  • 插入元素: 使用 Insert 方法在指定位置插入元素。
  • 删除元素: 使用 Remove 方法删除指定元素,使用 RemoveAt 方法删除指定位置的元素。
  • 查找元素: 使用 Contains 方法检查集合中是否包含指定元素,使用 IndexOf 方法获取元素的索引。
  1. // 添加多个元素
  2. names.AddRange(new List<string> { "Eve", "Frank" });
  3. // 在指定位置插入元素
  4. names.Insert(1, "Grace");
  5. // 删除指定元素
  6. names.Remove("Bob");
  7. // 删除指定位置的元素
  8. names.RemoveAt(0);
  9. // 查找元素
  10. bool containsAlice = names.Contains("Alice");
  11. int indexOfFrank = names.IndexOf("Frank");
  12. Console.WriteLine($"Contains Alice: {containsAlice}");
  13. Console.WriteLine($"Index of Frank: {indexOfFrank}");

示例:管理学生名单

  1. using System;
  2. using System.Collections.Generic;
  3. class StudentList
  4. {
  5. private List<string> students;
  6. public StudentList()
  7. {
  8. students = new List<string>();
  9. }
  10. public void AddStudent(string student)
  11. {
  12. students.Add(student);
  13. Console.WriteLine($"{student} 已加入学生名单。");
  14. }
  15. public void RemoveStudent(string student)
  16. {
  17. if (students.Remove(student))
  18. {
  19. Console.WriteLine($"{student} 已从学生名单中移除。");
  20. }
  21. else
  22. {
  23. Console.WriteLine($"{student} 不在学生名单中。");
  24. }
  25. }
  26. public void PrintStudents()
  27. {
  28. Console.WriteLine("学生名单:");
  29. foreach (var student in students)
  30. {
  31. Console.WriteLine(student);
  32. }
  33. }
  34. }
  35. class Program
  36. {
  37. static void Main()
  38. {
  39. StudentList studentList = new StudentList();
  40. studentList.AddStudent("Alice");
  41. studentList.AddStudent("Bob");
  42. studentList.PrintStudents();
  43. studentList.RemoveStudent("Alice");
  44. studentList.PrintStudents();
  45. }
  46. }

Dictionary

定义和初始化

Dictionary<TKey, TValue> 是一种键值对集合,通过键来快速访问值。以下是 Dictionary<TKey, TValue> 的定义和初始化方法:

  1. using System;
  2. using System.Collections.Generic;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. // 定义和初始化
  8. Dictionary<int, string> employees = new Dictionary<int, string>
  9. {
  10. { 1, "Alice" },
  11. { 2, "Bob" },
  12. { 3, "Charlie" }
  13. };
  14. // 添加键值对
  15. employees.Add(4, "Dave");
  16. // 访问值
  17. Console.WriteLine(employees[2]); // 输出:Bob
  18. // 遍历字典
  19. foreach (var kvp in employees)
  20. {
  21. Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}");
  22. }
  23. }
  24. }

常用操作

下面是一些 Dictionary<TKey, TValue> 的常用操作:

  • 添加键值对: 使用 Add 方法添加键值对。
  • 删除键值对: 使用 Remove 方法删除指定键的键值对。
  • 查找键值对: 使用 ContainsKey 方法检查字典是否包含指定键,使用 TryGetValue 方法获取指定键的值。
  1. // 添加键值对
  2. employees.Add(5, "Eve");
  3. // 删除指定键的键值对
  4. employees.Remove(1);
  5. // 查找键值对
  6. bool containsKey2 = employees.ContainsKey(2);
  7. if (employees.TryGetValue(3, out string value))
  8. {
  9. Console.WriteLine($"Key 3 maps to value: {value}");
  10. }
  11. Console.WriteLine($"Contains Key 2: {containsKey2}");

示例:管理员工信息

  1. using System;
  2. using System.Collections.Generic;
  3. class EmployeeDirectory
  4. {
  5. private Dictionary<int, string> employees;
  6. public EmployeeDirectory()
  7. {
  8. employees = new Dictionary<int, string>();
  9. }
  10. public void AddEmployee(int id, string name)
  11. {
  12. employees[id] = name;
  13. Console.WriteLine($"员工 {name}(ID: {id}) 已加入员工名录。");
  14. }
  15. public void RemoveEmployee(int id)
  16. {
  17. if (employees.Remove(id))
  18. {
  19. Console.WriteLine($"员工(ID: {id}) 已从员工名录中移除。");
  20. }
  21. else
  22. {
  23. Console.WriteLine($"员工(ID: {id}) 不在员工名录中。");
  24. }
  25. }
  26. public void PrintEmployees()
  27. {
  28. Console.WriteLine("员工名录:");
  29. foreach (var kvp in employees)
  30. {
  31. Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}");
  32. }
  33. }
  34. }
  35. class Program
  36. {
  37. static void Main()
  38. {
  39. EmployeeDirectory directory = new EmployeeDirectory();
  40. directory.AddEmployee(1, "Alice");
  41. directory.AddEmployee(2, "Bob");
  42. directory.PrintEmployees();
  43. directory.RemoveEmployee(1);
  44. directory.PrintEmployees();
  45. }
  46. }

HashSet

定义和初始化

HashSet<T> 是一种无序集合,不允许包含重复元素。以下是 HashSet<T> 的定义和初始化方法:

  1. using System;
  2. using System.Collections.Generic;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. // 定义和初始化
  8. HashSet<string> fruits = new HashSet<string> { "Apple", "Banana", "Cherry" };
  9. // 添加元素
  10. fruits.Add("Date");
  11. fruits.Add("Apple"); // 不会添加重复元素
  12. // 遍历集合
  13. foreach (var fruit in fruits)
  14. {
  15. Console.WriteLine(fruit);
  16. }
  17. }
  18. }

常用操作

下面是一些 HashSet<T> 的常用操作:

  • 添加元素: 使用 Add 方法添加元素。
  • 删除元素: 使用 Remove 方法删除指定元素。
  • 查找元素: 使用 Contains 方法检查集合中是否包含指定元素。
  1. // 添加元素
  2. fruits.Add("Elderberry");
  3. // 删除指定元素
  4. fruits.Remove("Banana");
  5. // 查找元素
  6. bool containsCherry = fruits.Contains("Cherry");
  7. Console.WriteLine($"Contains Cherry: {containsCherry}");

示例:管理水果集合

  1. using System;
  2. using System.Collections.Generic;
  3. class FruitBasket
  4. {
  5. private HashSet<string> fruits;
  6. public FruitBasket()
  7. {
  8. fruits = new HashSet<string>();
  9. }
  10. public void AddFruit(string fruit)
  11. {
  12. if (fruits.Add(fruit))
  13. {
  14. Console.WriteLine($"{fruit} 已加入水果篮。");
  15. }
  16. else
  17. {
  18. Console.WriteLine($"{fruit} 已存在于水果篮中。");
  19. }
  20. }
  21. public void RemoveFruit(string fruit)
  22. {
  23. if (fruits.Remove(fruit))
  24. {
  25. Console.WriteLine($"{fruit} 已从水果篮中移除。");
  26. }
  27. else
  28. {
  29. Console.WriteLine($"{fruit} 不在水果篮中。");
  30. }
  31. }
  32. public void PrintFruits()
  33. {
  34. Console.WriteLine("水果篮内容:");
  35. foreach (var fruit in fruits)
  36. {
  37. Console.WriteLine(fruit);
  38. }
  39. }
  40. }
  41. class Program
  42. {
  43. static void Main()
  44. {
  45. FruitBasket basket = new FruitBasket();
  46. basket.AddFruit("Apple");
  47. basket.AddFruit("Banana");
  48. basket.PrintFruits();
  49. basket.RemoveFruit("Apple");
  50. basket.PrintFruits();
  51. }
  52. }

集合的常用操作

对于所有集合类型(如 List<T>Dictionary<TKey, TValue>HashSet<T>),有一些常用的操作和方法,它们在不同的集合类型中表现各异,但基本思想是相似的:

  • 添加元素: 向集合中添加新元素。
  • 删除元素: 从集合中移除指定元素。
  • 查找元素: 验证集合中是否存在特定元素。
  • 遍历集合: 依次访问集合中的每个元素。

这些操作在日常编程中非常重要,掌握这些操作可以帮助你高效地管理和操作数据。


问题与建议

在学习集合时,你可能会遇到以下问题,请参考以下建议进行解决:

  1. 内存管理:集合在动态扩展时会消耗更多的内存,建议适当设置初始容量以提高性能。
  2. 线程安全:如果在多线程环境中使用集合,请使用线程安全的集合类,如 ConcurrentDictionary<TKey, TValue>
  3. 性能优化:选择合适的集合类型以提高性能,例如,当需要快速查找时优先使用 Dictionary<TKey, TValue>,而不是 List<T>

资源推荐

为了进一步提升对集合的理解和应用,建议参考以下资源:

  • Microsoft’s official C# documentation on collections: Introduction to Collections
  • C# in Depth by Jon Skeet - A great book providing in-depth knowledge about C# and its features.

在本章中,我们详细介绍了 C#中的集合类型,包括 List<T>Dictionary<TKey, TValue>HashSet<T>,并且演示了它们的定义、初始化和常用操作。集合是编程中非常重要的工具,掌握它们将极大提高你的编程效率和代码质量。

希望通过本章的学习,你已经能够熟练应用这些集合类型来解决实际编程问题。在接下来的章节中,我们将继续探讨更多高级主题,进一步提升你的 C#编程技能。