C#List

List的本质

是一个封装好的类 是一个可变类型的泛型数组 。不用ArrayList,用List

声明

cs 复制代码
using System.Collections.Generic
List<int> list = new List<int>();
List<string> list2 = new List<string>();

一个一个的增加

cs 复制代码
list.Add(1);
list.Add(2);
list2.Add("123");

范围增加

cs 复制代码
 list2.Add("123");
 List<string> listStr = new List<string>();
 listStr.Add("123");
 list2.AddRange(listStr);

指定位置插入

cs 复制代码
list.Insert(0, 999);
Console.WriteLine(list[0]);

删除

移除指定元素

cs 复制代码
list.Remove(1);

移除指定位置的元素

cs 复制代码
 list.RemoveAt(0);

清空

cs 复制代码
list.Clear();

查找

得到指定位置元素

cs 复制代码
Console.WriteLine(list[0]);

查找元素是否存在

cs 复制代码
if (list.Contains(1)) { Console.WriteLine("存在元素 1"); }

正向查找元素

找到返回位置 找不到返回-1

cs 复制代码
int index = list.IndexOf(5);

反向查找元素

cs 复制代码
index = list.LastIndexOf(2);

cs 复制代码
Console.WriteLine(list[0]);
list[0] = 99;
Console.WriteLine(list[0]);

遍历

count是实际存在的个数,Capacity是实际的数组容量

cs 复制代码
Console.WriteLine(list.Count);

Console.WriteLine(list.Capacity);

for(int i = 0; i < list.Count; i++)
{
    Console.WriteLine(list[i]);

}
foreach(int item in list)
{
    Console.WriteLine(item);
}
相关推荐
hez20104 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉9 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫10 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫11 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62511 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021111 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠12 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫14 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech14 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf16 天前
C#摸鱼实录——IoC与DI案例详解
c#