【C#零基础从入门到精通】(十八)——C#list集合详解
在C#中,集合(Collection)是一种用于存储和管理一组元素的数据结构。List<T>
是.NET框架中非常常用的一种泛型集合类型,它提供了动态数组的功能,能够自动调整大小以容纳更多的元素。List<T>
属于System.Collections.Generic命名空间,因此在使用之前需要引入该命名空间。
1. 引入命名空间
在使用 List<T>
之前,需要引入 System.Collections.Generic
命名空间,示例代码如下:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 后续使用 List<T> 的代码将在这里编写
}
}
2. 创建 List<T>
对象
可以使用无参构造函数、带有初始容量参数的构造函数,或者通过传入一个实现了 IEnumerable<T>
接口的集合来创建 List<T>
对象。
// 使用无参构造函数创建 List<int> 对象
List<int> intList1 = new List<int>();
// 使用带有初始容量参数的构造函数创建 List<int> 对象
List<int> intList2 = new List<int>(10); // 初始容量为 10
// 通过传入一个实现了 IEnumerable<T> 接口的集合来创建 List<int> 对象
int[] array = { 1, 2, 3, 4, 5 };
List<int> intList3 = new List<int>(array);
3. 添加元素
Add
方法:用于向List<T>
末尾添加单个元素。
List<string> stringList = new List<string>();
stringList.Add("apple");
stringList.Add("banana");
AddRange
方法:用于向List<T>
末尾添加多个元素,参数是一个实现了IEnumerable<T>
接口的集合。
List<int> numbers1 = new List<int> { 1, 2, 3 };
List<int> numbers2 = new List<int> { 4, 5, 6 };
numbers1.AddRange(numbers2);
4. 访问元素
可以通过索引来访问 List<T>
中的元素,索引从 0 开始。
List<int> intList = new List<int> { 10, 20, 30 };
int firstElement = intList[0]; // 访问第一个元素
int secondElement = intList[1]; // 访问第二个元素
5. 修改元素
同样可以通过索引来修改 List<T>
中的元素。
List<string> fruitList = new List<string> { "apple", "banana" };
fruitList[1] = "cherry"; // 将第二个元素修改为 "cherry"
6. 删除元素
Remove
方法:根据元素的值来删除指定的元素,如果存在多个相同值的元素,只会删除第一个匹配的元素。
List<int> numList = new List<int> { 10, 20, 10 };
numList.Remove(10); // 删除第一个值为 10 的元素
RemoveAt
方法:根据元素的索引来删除指定位置的元素。
List<char> charList = new List<char> { 'a', 'b', 'c' };
charList.RemoveAt(1); // 删除索引为 1 的元素(即第二个元素 'b')
RemoveRange
方法:删除指定范围内的元素。
List<int> rangeList = new List<int> { 1, 2, 3, 4, 5 };
rangeList.RemoveRange(1, 3); // 从索引为 1 的位置开始,删除 3 个元素
RemoveAll
方法:删除满足指定条件的所有元素,需要传入一个Predicate<T>
委托。
List<int> allList = new List<int> { 1, 2, 3, 4, 5 };
allList.RemoveAll(x => x % 2 == 0); // 删除所有偶数元素
7. 查找元素
Contains
方法:判断List<T>
中是否包含指定的元素。
List<string> wordList = new List<string> { "hello", "world" };
bool contains = wordList.Contains("hello"); // 返回 true
IndexOf
方法:查找指定元素第一次出现的索引位置,如果未找到则返回 -1。
List<int> findList = new List<int> { 10, 20, 10 };
int index = findList.IndexOf(10); // 返回 0
LastIndexOf
方法:查找指定元素最后一次出现的索引位置,如果未找到则返回 -1。
List<int> lastList = new List<int> { 10, 20, 10 };
int lastIndex = lastList.LastIndexOf(10); // 返回 2
Find
方法:查找满足指定条件的第一个元素,需要传入一个Predicate<T>
委托。
List<int> searchList = new List<int> { 1, 2, 3, 4, 5 };
int firstEven = searchList.Find(x => x % 2 == 0); // 返回第一个偶数 2
FindAll
方法:查找满足指定条件的所有元素,返回一个新的List<T>
,需要传入一个Predicate<T>
委托。
List<int> allEvenList = searchList.FindAll(x => x % 2 == 0); // 返回包含所有偶数的新列表
8. 获取元素数量和容量
Count
属性:获取List<T>
中实际包含的元素数量。
List<int> sizeList = new List<int> { 1, 2, 3 };
int count = sizeList.Count; // 返回 3
Capacity
属性:获取或设置List<T>
可以包含的元素数量。当添加元素时,如果元素数量超过当前容量,List<T>
会自动增加容量。
List<int> capList = new List<int>(10);
int capacity = capList.Capacity; // 返回 10
capList.Add(1);
// 当元素数量超过容量时,容量会自动增加
for (int i = 0; i < 15; i++)
{
capList.Add(i);
}
capacity = capList.Capacity; // 容量会根据实际情况增加
9. 遍历 List<T>
可以使用 for
循环、foreach
循环、for-each
语句或者 List<T>
的 ForEach
方法来遍历 List<T>
。
List<int> loopList = new List<int> { 1, 2, 3 };
// 使用 for 循环遍历
for (int i = 0; i < loopList.Count; i++)
{
Console.WriteLine(loopList[i]);
}
// 使用 foreach 循环遍历
foreach (int item in loopList)
{
Console.WriteLine(item);
}
// 使用 ForEach 方法遍历
loopList.ForEach(item => Console.WriteLine(item));
10. 排序和反转
Sort
方法:对List<T>
中的元素进行排序,默认使用元素类型的IComparable<T>
实现。
List<int> sortList = new List<int> { 3, 1, 2 };
sortList.Sort(); // 按升序排序
也可以传入一个 Comparison<T>
委托来指定自定义的排序规则。
List<string> customSortList = new List<string> { "banana", "apple", "cherry" };
customSortList.Sort((x, y) => x.Length.CompareTo(y.Length)); // 按字符串长度排序
Reverse
方法:反转List<T>
中元素的顺序。
List<int> reverseList = new List<int> { 1, 2, 3 };
reverseList.Reverse(); // 元素顺序变为 3, 2, 1
11. List<T>
的优缺点
优点
- 类型安全:
List<T>
是泛型集合,在编译时会进行类型检查,避免了类型转换错误和运行时异常。 - 性能较好:相比于非泛型的
ArrayList
,List<T>
避免了装箱和拆箱操作,提高了性能。 - 动态大小:可以根据需要动态调整大小,无需预先指定固定的容量。
缺点
- 插入和删除效率较低:在
List<T>
中间插入或删除元素时,需要移动后续元素,时间复杂度为 \(O(n)\)。
综上所述,List<T>
是 C# 中非常常用的集合类,它提供了丰富的功能和良好的性能,适用于大多数需要动态数组的场景