using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace L_List
{
class Program
{
private static void PrintList<T>(List<T> nList)
{
if (nList.Count == 0)
Console.WriteLine("列表为空数据");
for (int i = 0; i < nList.Count; i++)
{
Console.Write(nList[i] + "\t");
}
Console.WriteLine(" ");
}
static void Main(string[] args)
{
Console.WriteLine("List的使用");
#region 1.List的本质
// List是C#帮助我们封装好的类
// 它的本质就是一个 可变类型的范型数组
// List类帮助我们实现了很多方法
// 比如泛型数组的增删查改
#endregion
#region 2.声明
// 需要引用命名空间
// using System.Collections.Generic;
List<int> nList = new List<int>();
List<string> strList = new List<string>();
List<bool> boolList = new List<bool>();
#endregion
#region 3.增删改查
#region 增
Console.WriteLine("--------------------- 增");
nList.Add(1);
nList.Add(2);
nList.Add(3);
nList.Add(4);
nList.Add(1);
Console.WriteLine("增加完成后, 显示列表");
PrintList<int>(nList);
nList.Insert(3, 999);
PrintList<int>(nList);
List<string> strRangeList = new List<string>();
strRangeList.Add("10");
strRangeList.Add("20");
strRangeList.Add("30");
Console.WriteLine("AddRange增加后 --");
strList.AddRange(strRangeList);
PrintList<string>(strList);
#endregion
#region 删
Console.WriteLine("--------------------- 删");
// 移除指定元素 删除第一个指定的元素
nList.Remove(1);
Console.WriteLine("删除1, 后显示");
PrintList<int>(nList);
// 删除指定位置的元素
int nIndex = nList.IndexOf(4);
if( nIndex !=-1 )
nList.RemoveAt(nIndex);
Console.WriteLine("删除4, 后显示");
PrintList<int>(nList);
// 删除所有数据
strList.Clear();
Console.WriteLine("清空字符串数组");
PrintList<string>(strList);
#endregion
#region 查
nList.Add(2);
Console.WriteLine("--------------------- 查");
PrintList<int>(nList);
// 得到指定位置的元素
Console.WriteLine("查--- 0号元素的值:" + nList[0]);
// 查看元素是否存在
if (nList.Contains(3))
{
Console.WriteLine("查--- 值为3的元素存在 ");
}
// 正向查找元素位置 找不到返回 -1
int index3 = nList.IndexOf(3);
Console.WriteLine("查--- 值为3的元素的索引:" + index3);
int index5 = nList.IndexOf(5);
Console.WriteLine("查--- 值为5的元素的索引:" + index5);
// 反向查找元素位置 找不到返回 -1
int indexLast = nList.LastIndexOf(2);
Console.WriteLine("反向查找--- 值为2的元素的索引:" + indexLast);
#endregion
#region 改
Console.WriteLine("-------------------------改");
PrintList<int>(nList);
nList[0] = 99;
PrintList<int>(nList);
#endregion
#endregion
#region 4.遍历
Console.WriteLine("-------------------------遍历");
// 长度
Console.WriteLine("数组长度:" + nList.Count);
// 容量
Console.WriteLine("数组容量:" + nList.Capacity);
// []遍历
Console.WriteLine("索引遍历");
for (int i = 0; i < nList.Count; i++)
{
Console.Write(nList[i] + "\t");
}
Console.WriteLine(" ");
// 迭代器方式 遍历
Console.WriteLine("迭代器遍历");
foreach (int item in nList)
{
Console.Write(item + "\t");
}
Console.WriteLine("");
#endregion
Console.ReadKey();
}
}
}
C# 泛型List的基本使用
于 2022-05-15 19:28:18 首次发布
本文详细介绍了C#中List类的使用,包括声明、增删改查操作,以及遍历和查找方法。通过示例代码展示了如何添加、删除、修改和查找列表元素,并演示了使用AddRange方法和Insert方法来批量添加元素。此外,还涵盖了列表的遍历,包括使用索引和迭代器的方式。
摘要由CSDN通过智能技术生成