第 8 部分:C# 中的集合
C# 中的集合提供了强大的工具来高效地管理和组织数据。它们使开发人员能够轻松处理对象组,无论您需要固定大小的数组还是动态灵活的数据结构(如列表和字典)。在本文中,我们将探讨 C# 中的主要集合类型、它们的方法和实际用例。
1. C 语言中的集合类型
1.1 数组
**数组** 是相同类型元素的固定大小集合。它适用于项目数量已知且不会改变的情况。
例子:
int[] numbers = {1, 2, 3, 4, 5}; foreach (int number in numbers) { Console.WriteLine(number); }
主要方法和属性:
1.2 列表
**List** 是一个可以增大或缩小的动态集合。列表是 `System.Collections.Generic` 命名空间的一部分,比数组更通用。
例子:
Listnames = new List {"John", "Adrian", "Charlie"}; names.Add("Adrian"); foreach (string name in names) { Console.WriteLine(name); }
主要方法:
1.3 字典
**字典** 是键值对的集合,其中每个键都是唯一的。字典是需要快速查找的场景的理想选择。
例子:
Dictionarystudents = new Dictionary { {1, "Adrian"}, {2, "John"}, {3, "Charlie"} }; if (students.ContainsKey(2)) { Console.WriteLine($"Student ID 2: {students[2]}"); }
主要方法:
**性能说明**:字典由于其散列机制而提供快速查找,使其适用于频繁搜索键的场景。
1.4 套
**HashSet** 是包含唯一元素且不允许重复的集合。它针对快速查找进行了优化。
例子:
HashSetuniqueNumbers = new HashSet {1, 2, 3, 3, 4}; foreach (int number in uniqueNumbers) { Console.WriteLine(number); }
主要方法:
**性能注意事项**:当您需要确保集合的唯一性时,请使用“HashSet”。
2. 收集方法及其用途
跨集合的通用方法:
**(LINQ将在后续文章中讨论)**
LINQ 筛选的示例:
Listnumbers = new List {1, 2, 3, 4, 5}; var evenNumbers = numbers.Where(n => n % 2 == 0); foreach (int number in evenNumbers) { Console.WriteLine(number); }
3. 实例:使用集合进行数据管理
场景:管理学生名册
此示例演示如何使用多种类型的集合来管理学生数据。
例子:
using System; using System.Collections.Generic; class Program { static void Main() { // Store student data Dictionarystudents = new Dictionary { {1, "Adrian"}, {2, "John"}, {3, "Charlie"} }; // Add new students students.Add(4, "Diana"); // All students Console.WriteLine("Student Roster:"); foreach (var student in students) { Console.WriteLine($"ID: {student.Key}, Name: {student.Value}"); } // Check if a student exists if (students.ContainsKey(2)) { Console.WriteLine("Student ID 2 is in the roster."); } // Remove a student students.Remove(3); Console.WriteLine("Updated Roster:"); foreach (var student in students) { Console.WriteLine($"ID: {student.Key}, Name: {student.Value}"); } } } /* Student Roster: ID: 1, Name: Adrian ID: 2, Name: John ID: 3, Name: Charlie ID: 4, Name: Diana Student ID 2 is in the roster. Updated Roster: ID: 1, Name: Adrian ID: 2, Name: John ID: 4, Name: Diana */
4. 高级主题
线程安全集合
对于需要线程安全操作的应用程序,请考虑使用“ConcurrentDictionary”或“System.Collections.Concurrent”命名空间中的其他线程安全集合。
例子:
using System; using System.Collections.Concurrent; class Program { static void Main() { ConcurrentDictionarysafeDict = new ConcurrentDictionary (); safeDict.TryAdd(1, "Adrian"); safeDict.TryAdd(2, "John"); foreach (var item in safeDict) { Console.WriteLine($"Key: {item.Key}, Value: {item.Value}"); } } }
不可变集合
为了确保集合在创建后不能被修改,请使用“System.Collections.Immutable”中的不可变集合。
例子:
using System.Collections.Immutable; ImmutableListimmutableNames = ImmutableList.Create("Adrian", "John", "Charlie"); foreach (var name in immutableNames) { Console.WriteLine(name); }