在C#中,List 是一个泛型集合类,属于 System.Collections.Generic 命名空间。它提供了一系列方法来操作元素的列表,包括添加、移除、排序和搜索等。由于List是泛型的,它只能存储指定类型的元素,这提供了类型安全和性能优势。
以下是C#中List的一些基本操作:
初始化:
List<int> list = new List<int>();
添加元素 - 使用 Add 方法将元素添加到列表的末尾:
list.Add(1);
插入元素 - 使用 Insert 方法在特定索引位置插入一个元素:
list.Insert(0, 0); // 在索引0的位置插入元素0
访问元素 - 使用索引直接访问列表中的元素:
int item = list[0]; // 获取第一个元素
移除元素 - 使用 Remove 方法移除列表中的特定元素:
list.Remove(1); // 移除元素1
移除特定索引的元素 - 使用 RemoveAt 方法移除位于特定索引的元素:
list.RemoveAt(0); // 移除索引0处的元素
获取元素索引 - 使用 IndexOf 方法获取特定元素在列表中的索引:
int index = list.IndexOf(1); // 获取元素1的索引
获取列表中元素的数量 - 使用 Count 属性:
int count = list.Count;
清空列表 - 使用 Clear 方法:
list.Clear();
克隆列表 - 使用 List 的 ToList 方法或 MemberwiseClone 方法:
List<int> clonedList = list.ToList(); // 创建一个浅拷贝
遍历列表 - 使用 foreach 循环遍历列表中的所有元素:
foreach (int item in list)
{
Console.WriteLine(item);
}
查找元素 - 使用 FindIndex 或 Find 方法查找满足特定条件的第一个元素:
int foundIndex = list.FindIndex(x => x > 5);
下面是一个简单的C# List 使用示例:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
// 添加元素
list.Add(6);
// 插入元素
list.Insert(1, 0); // 在索引1的位置插入元素0
// 访问元素
int firstItem = list[0];
// 移除特定元素
list.Remove(3);
// 移除特定索引的元素
list.RemoveAt(1);
// 获取元素索引
int index = list.IndexOf(6);
// 打印列表中的所有元素
foreach (int item in list)
{
Console.WriteLine(item);
}
// 获取列表中元素的数量
int count = list.Count;
// 清空列表
list.Clear();
// 克隆列表
List<int> clonedList = list.ToList();
Console.WriteLine("Original Count: " + list.Count);
Console.WriteLine("Cloned Count: " + clonedList.Count);
}
}
想了解更多游戏开发知识,可以扫描下方二维码,免费领取游戏开发4天训练营课程