C# List集合

一、简介

List是一种泛型集合类,用于存储一组相同类型的元素

二、使用

1、创建List

  • 创建List对象时,需要指定集合中元素的类型
csharp 复制代码
List<int> ints = new List<int>();

List<string> strings = new List<string>();

2、添加元素

2.1 使用Add()方法添加

csharp 复制代码
List<int> ints = new List<int>();
ints.Add(1);
ints.Add(2);
ints.Add(3);

2.2 使用AddRange()方法添加

csharp 复制代码
List<int> ints = new List<int>();
ints.AddRange(1,2,3);

3、删除元素

3.1 删除指定元素

  • Remove 方法用于删除集合中的指定元素,如果集合中中存在多个相同的元素,只会删除第一个
csharp 复制代码
List<int> ints = new List<int>();
ints.AddRange(1, 2, 3, 1, 2, 3);
ints.Remove(1);
  • RemoveAll 方法用于删除集合中所有匹配到的元素
csharp 复制代码
List<int> ints = new List<int>();
ints.AddRange(1, 2, 3, 1, 2, 3);
ints.RemoveAll(x => x == 1);

3.2 删除指定索引

  • RemoveAt 方法用于删除集合中指定索引位置的元素,索引序号从零开始
csharp 复制代码
//此时会删除列表中索引为2的元素 3
List<int> ints = new List<int>();
ints.AddRange(1, 2, 3, 1, 2, 3);
ints.RemoveAt(2);
  • RemoveRange 方法用于删除集合中从指定索引位置开始,指定长度的元素,索引序号从零开始
csharp 复制代码
//此时会从列表中索引为0的元素开始删除,删除2个元素,即1、2会被删除
List<int> ints = new List<int>();
ints.AddRange(1, 2, 3, 1, 2, 3);
ints.RemoveRange(0, 2);

3.3 清空集合

  • Clear 方法用于清空整个集合
csharp 复制代码
//此时会删除集合中的所有元素
List<int> ints = new List<int>();
ints.AddRange(1, 2, 3, 1, 2, 3);
ints.Clear();

4、遍历集合

4.1 for 循环

  • 依次输出集合中的元素
csharp 复制代码
List<int> ints = new List<int>();
ints.AddRange(1, 2, 3, 1, 2, 3);
for (int i = 0; i < ints.Count; i++)
{
    Console.WriteLine(ints[i]);
}

4.2 foreach 循环

  • 依次输出集合中的元素
csharp 复制代码
List<int> ints = new List<int>();
ints.AddRange(1, 2, 3, 1, 2, 3);
foreach (int num in ints)
{
    Console.WriteLine(num);
}

5、常用方法

5.1 Count

csharp 复制代码
//获取集合中元素的个数,此时结果为6
List<int> ints = new List<int>() { 1, 2, 3, 4, 5, 6 };
ints.Count();

5.2 Sort

csharp 复制代码
//对集合中的元素进行排序,默认从小到大
List<int> ints = new List<int>() { 1, 2, 3, 4, 5, 6 };
ints.Sort();

5.3 Reverse

csharp 复制代码
//反转集合中的元素
List<int> ints = new List<int>() { 1, 2, 3, 4, 5, 6 };
ints.Reverse();

5.4 Contains

csharp 复制代码
//判断集合中是否包含某元素
List<int> ints = new List<int>() { 1, 2, 3, 4, 5, 6 };
bool b = ints.Contains(5);

5.5 IndexOf

csharp 复制代码
//获取集合中指定元素的索引,不存在则为-1
List<int> ints = new List<int>() { 1, 2, 3, 4, 5, 6 };
int index = ints.IndexOf(5);
相关推荐
Risehuxyc16 小时前
HttpClient怎么传POST参数
c#
小灰灰搞电子3 天前
C++ initializer_list 详解
c++·list
zdr尽职尽责4 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
BruceNeter6 天前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net
wo_jack6 天前
C++ 入门笔记(十八):list 进阶 —— const 迭代器、operator-> 与 clear 的坑
数据结构·c++·面试·stl·list
2601_967980117 天前
python list如何赋值
python·list·列表推导式·赋值·切片赋值
何以解忧唯有撸码7 天前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
国家一级摸鱼选手8 天前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库8 天前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc8 天前
C# 发展历史
开发语言·c#