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);
}
相关推荐
devilnumber16 分钟前
Java 递归算法 详解 + 核心要点 + 实战运用 + 避坑指南
java·开发语言·算法
asdfg12589632 小时前
JavaBean是什么?怎么理解?有什么用途?
java·开发语言
dsyyyyy11012 小时前
JavaScript变量
开发语言·javascript·ecmascript
z落落3 小时前
C#WinForm 窗体切换与窗体传值(登录跳转案例)+WinForm 窗体传值(从上往下传、从下往上传)
开发语言·windows·c#
allway23 小时前
How to Echo Multiline to a File in Bash [3 Methods]
开发语言·chrome·bash
weixin_462446233 小时前
手把手教你用 Bash 脚本自动更新 /etc/hosts —— 自动绑定网卡 IP 与节点名
开发语言·tcp/ip·bash
一个梦醒了3 小时前
安装git bash选项推荐
开发语言·git·bash
ct9784 小时前
React 状态管理方案深度对比
开发语言·前端·react
数量技术宅4 小时前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python
华如锦4 小时前
面了很多 Java转AI Agent方向,一些面试题总结
java·开发语言·人工智能·python·ai