C#List<T> 常用实例方法1
适配C#7.3,直接复制运行
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 初始化集合
List<int> nums = new List<int> { 2, 5, 1, 5, 8 };
#region 1. 添加元素
nums.Add(9); // 尾部单个添加
nums.AddRange(new int[] { 3, 7 });// 批量添加
nums.Insert(1, 6); // 指定下标插入
Console.WriteLine("添加后:"+string.Join(",", nums));
#endregion
#region 2. 删除元素
nums.Remove(5); // 删除第一个匹配项
nums.RemoveAt(2); // 按下标删除
nums.RemoveAll(x => x > 6); // 删除所有大于6的数
Console.WriteLine("删除后:"+string.Join(",", nums));
#endregion
#region 3. 查询判断
bool hasOne = nums.Contains(1);
int idx = nums.IndexOf(2);
bool exist = nums.Exists(x => x == 3);
int first = nums.Find(x => x > 2);
List<int> allMatch = nums.FindAll(x => x % 2 == 0);
Console.WriteLine($"包含1:{hasOne},2下标:{idx},存在3:{exist}");
Console.WriteLine("所有偶数:"+string.Join(",", allMatch));
#endregion
#region 4. 排序、反转、截取
nums.Sort(); // 默认升序
nums.Reverse(); // 反转顺序
List<int> sub = nums.GetRange(1, 2);// 截取下标1开始2个元素
Console.WriteLine("排序反转后:"+string.Join(",", nums));
Console.WriteLine("截取子集:"+string.Join(",", sub));
#endregion
#region 5. 遍历、转换、清空
Console.Write("ForEach遍历:");
nums.ForEach(x => Console.Write(x+" "));
int[] arr = nums.ToArray(); // 转数组
List<int> newList = nums.ToList();// 生成新列表
nums.Clear(); // 清空集合
Console.WriteLine($"\n原集合清空后数量:{nums.Count}");
#endregion
Console.ReadLine();
}
}
运行输出
添加后:2,6,5,1,5,8,9,3,7
删除后:2,1,3
包含1:True,2下标:0,存在3:True
所有偶数:2
排序反转后:3,2,1
截取子集:2,1
ForEach遍历:3 2 1
原集合清空后数量:0

浙公网安备 33010602011771号