温馨提示×

c# arraylist怎样进行遍历操作

c#
小樊
90
2024-11-15 23:47:14
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,遍历ArrayList的方法有很多种。以下是一些常见的方法:

  1. 使用for循环遍历:
ArrayList myArrayList = new ArrayList();
// 添加元素到ArrayList
myArrayList.Add("Apple");
myArrayList.Add("Banana");
myArrayList.Add("Cherry");

for (int i = 0; i < myArrayList.Count; i++)
{
    Console.WriteLine(myArrayList[i]);
}
  1. 使用foreach循环遍历:
ArrayList myArrayList = new ArrayList();
// 添加元素到ArrayList
myArrayList.Add("Apple");
myArrayList.Add("Banana");
myArrayList.Add("Cherry");

foreach (object item in myArrayList)
{
    Console.WriteLine(item);
}
  1. 使用迭代器遍历:
ArrayList myArrayList = new ArrayList();
// 添加元素到ArrayList
myArrayList.Add("Apple");
myArrayList.Add("Banana");
myArrayList.Add("Cherry");

IEnumerator iterator = myArrayList.GetEnumerator();
while (iterator.MoveNext())
{
    Console.WriteLine(iterator.Current);
}

以上三种方法都可以实现遍历ArrayList的目的,你可以根据自己的需求和喜好选择合适的方法。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c#中arraylist怎么删除重复值

0