Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 遍历list

作者:硝烟   发布日期:2025-08-29   浏览:112

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++;
        }
    }
}

解释说明:

  1. 创建List:首先我们创建了一个名为fruitsList<string>,其中包含了几个水果名称。
  2. 使用foreach遍历List:这是最常用的方法之一。它会自动遍历集合中的每个元素,无需手动管理索引。
  3. 使用for循环遍历List:通过索引访问List中的元素。这种方法适用于需要知道当前元素位置的情况。
  4. 使用while循环遍历List:类似于for循环,但使用了while语句来控制循环条件。

上一篇:c#获取list集合中某一元素的值

下一篇:c#实例

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

c# rectangle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站