using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个包含字符串的List
List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Grape" };
// 方法1: 使用foreach遍历List
Console.WriteLine("使用foreach遍历List:");
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
// 方法2: 使用for循环遍历List
Console.WriteLine("\n使用for循环遍历List:");
for (int i = 0; i < fruits.Count; i++)
{
Console.WriteLine(fruits[i]);
}
// 方法3: 使用while循环遍历List
Console.WriteLine("\n使用while循环遍历List:");
int index = 0;
while (index < fruits.Count)
{
Console.WriteLine(fruits[index]);
index++;
}
}
}
fruits
的List<string>
,其中包含了几个水果名称。foreach
遍历List:这是最常用的方法之一。它会自动遍历集合中的每个元素,无需手动管理索引。for
循环遍历List:通过索引访问List中的元素。这种方法适用于需要知道当前元素位置的情况。while
循环遍历List:类似于for
循环,但使用了while
语句来控制循环条件。下一篇:c#实例
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站