在C#中,List 是一个非常常用且强大的集合类型,它位于 System.Collections.Generic 命名空间中。List 提供了一个可以动态调整大小的数组,允许你轻松地添加、删除和访问列表中的元素。
下面是一些关于如何使用 List 的基本用法
定义和初始化
using System;
using System.Collections.Generic;
class Program {
static void Main() {
// 定义一个整型的List并初始化
List<int> intList = new List<int> {1, 2, 3};
// 或者先定义再添加元素
List<string> stringList = new List<string>();
stringList.Add("Hello");
stringList.Add("World");
}
}
添加元素
intList.Add(4);
stringList.Add("!");
访问和修改元素
intList.Add(4);
stringList.Add("!");
访问和修改元素
可以通过索引来访问或修改 List 中的元素,索引从 0 开始。
Console.WriteLine(intList[0]); // 输出: 1
stringList[1] = "CSharp"; // 修改第二个元素
删除元素
可以使用 Remove() 按值删除第一个匹配的元素,或者使用 RemoveAt() 按索引删除元素。
intList.Remove(2); // 移除值为2的元素
stringList.RemoveAt(0); // 移除第一个元素
遍历 List
可以使用 foreach 循环或其他循环结构遍历 List 中的元素。
foreach (var item in intList) {
Console.WriteLine(item);
}
或者使用for循环
for (int i = 0; i < stringList.Count; i++) {
Console.WriteLine(stringList[i]);
}
其他常用属性和方法
- Count: 获取 List 中实际包含的元素数量。
- Capacity: 获取或设置内部数据结构分配的元素总数,该值至少与 Count
一样大。
Clear(): 清除所有元素。
以上是 List 功能的一部分,它还支持很多其他有用的方法和属性,能够满足各种不同的需求。
记得在使用前引入 System.Collections.Generic 命名空间。