集合是存储和管理一组相关数据的容器。在 C# 中,集合提供了灵活的方式来存储、操作和访问数据。集合类位于 System.Collections.Generic 和 System.Collections 命名空间中。本章将详细介绍几种常见的集合类型及其使用方法。
List
List 是一种动态数组,可以根据需要自动扩展或缩小其容量。List 类位于 System.Collections.Generic 命名空间中。
定义和初始化
你可以通过多种方式定义和初始化一个 List:
// www.javascriptcn.com code example
// 使用默认构造函数
List<int> numbers = new List<int>();
// 使用集合初始化器
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
// 从数组创建
int[] values = { 1, 2, 3 };
List<int> intList = new List<int>(values);添加和移除元素
List 提供了多种添加和移除元素的方法:
// www.javascriptcn.com code example
// 添加单个元素
numbers.Add(4);
// 添加多个元素
numbers.AddRange(new int[] { 5, 6 });
// 移除指定索引处的元素
numbers.RemoveAt(0);
// 移除第一个匹配项
numbers.Remove(6);
// 清空所有元素
numbers.Clear();访问元素
可以通过索引或遍历来访问 List 中的元素:
// 通过索引访问
int firstNumber = numbers[0];
// 遍历所有元素
foreach (var num in numbers)
{
Console.WriteLine(num);
}其他常用方法
List 类还提供了一些其他有用的方法:
// 查找指定元素的位置 int index = numbers.IndexOf(5); // 检查是否包含某个元素 bool contains = numbers.Contains(3); // 获取元素数量 int count = numbers.Count;
Array
Array 是一种固定长度的数据结构,适用于已知大小的数据集。Array 类位于 System 命名空间中。
定义和初始化
可以使用多种方式定义和初始化一个 Array:
// www.javascriptcn.com code example
// 使用数组字面量
int[] nums = { 1, 2, 3 };
// 使用 new 关键字
string[] words = new string[3];
words[0] = "Hello";
words[1] = "World";
words[2] = "!";
// 初始化多维数组
int[,] matrix = new int[3, 3];
matrix[0, 0] = 1;
matrix[0, 1] = 2;
matrix[0, 2] = 3;访问和修改元素
可以使用索引来访问和修改 Array 中的元素:
// www.javascriptcn.com code example // 访问元素 int firstNum = nums[0]; // 修改元素 nums[0] = 10; // 多维数组 int element = matrix[0, 0]; matrix[0, 0] = 100;
其他常用方法
Array 类提供了一些有用的静态方法来处理数组:
// www.javascriptcn.com code example // 复制数组 int[] copy = new int[nums.Length]; Array.Copy(nums, copy, nums.Length); // 排序数组 Array.Sort(nums); // 反转数组 Array.Reverse(nums);
Dictionary
Dictionary 是一种键值对(key-value pair)的集合,每个元素都有一个唯一的键和对应的值。Dictionary 类位于 System.Collections.Generic 命名空间中。
定义和初始化
可以通过多种方式定义和初始化一个 Dictionary:
// www.javascriptcn.com code example
// 使用默认构造函数
Dictionary<string, int> ages = new Dictionary<string, int>();
// 使用集合初始化器
Dictionary<string, string> countries = new Dictionary<string, string>
{
{ "China", "Beijing" },
{ "USA", "Washington" }
};
// 从数组创建
KeyValuePair<string, int>[] pairs = {
new KeyValuePair<string, int>("Alice", 25),
new KeyValuePair<string, int>("Bob", 30)
};
Dictionary<string, int> dict = new Dictionary<string, int>(pairs);添加和移除元素
Dictionary 提供了多种添加和移除元素的方法:
// www.javascriptcn.com code example
// 添加键值对
ages.Add("Charlie", 35);
// 更新键值对
ages["Alice"] = 26;
// 移除指定键的元素
ages.Remove("Bob");
// 清空所有元素
ages.Clear();访问元素
可以通过键来访问 Dictionary 中的元素:
// www.javascriptcn.com code example
// 通过键访问
int age = ages["Alice"];
// 检查键是否存在
bool exists = ages.ContainsKey("Charlie");
// 遍历所有元素
foreach (KeyValuePair<string, int> pair in ages)
{
Console.WriteLine($"Name: {pair.Key}, Age: {pair.Value}");
}其他常用方法
Dictionary 类还提供了一些其他有用的方法:
// 获取元素数量
int count = ages.Count;
// 查找指定键的值
bool tryGetResult = ages.TryGetValue("Alice", out int ageValue);HashSet
HashSet 是一种不包含重复元素的集合。HashSet 类位于 System.Collections.Generic 命名空间中。
定义和初始化
可以通过多种方式定义和初始化一个 HashSet:
// www.javascriptcn.com code example
// 使用默认构造函数
HashSet<int> set = new HashSet<int>();
// 使用集合初始化器
HashSet<string> fruits = new HashSet<string> { "Apple", "Banana", "Orange" };
// 从数组创建
string[] items = { "Red", "Green", "Blue" };
HashSet<string> colors = new HashSet<string>(items);添加和移除元素
HashSet 提供了多种添加和移除元素的方法:
// 添加元素 set.Add(1); // 移除指定元素 set.Remove(1); // 清空所有元素 set.Clear();
访问元素
由于 HashSet 不支持通过索引访问,通常使用迭代器或遍历来访问元素:
// 遍历所有元素
foreach (var item in set)
{
Console.WriteLine(item);
}
// 检查元素是否存在
bool exists = set.Contains(2);其他常用方法
HashSet 类还提供了一些其他有用的方法:
// 获取元素数量 int count = set.Count;
结论
本章介绍了几种常见的集合类型:List、Array、Dictionary 和 HashSet。这些集合类型提供了丰富的功能,使得数据管理和操作变得更加便捷。根据具体需求选择合适的集合类型,可以提高代码的效率和可读性。