溫馨提示×

List在C#中如何實現(xiàn)循環(huán)遍歷

c#
小樊
154
2024-08-13 16:34:40
欄目: 編程語言

在C#中,可以使用foreach循環(huán)來遍歷List中的元素。例如:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

foreach (int number in numbers)
{
    Console.WriteLine(number);
}

這段代碼會輸出List中的每一個元素。當(dāng)然,你也可以使用for循環(huán)來遍歷List:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

for (int i = 0; i < numbers.Count; i++)
{
    Console.WriteLine(numbers[i]);
}

以上兩種方法都可以實現(xiàn)循環(huán)遍歷List中的元素。

0