C# loop List example

In this source code example, we will demonstrate several ways to loop over a C# list.

C# loop List of strings example

The following example demonstrates several ways to loop over a C# list:
using System;
using System.Collections.Generic;

public class ListDemo
{
    public static void Main(string[] args)
    {
        var fruits = new List<string> { "banana", "mango", "apple", "watermelon" };

        fruits.ForEach(f => Console.WriteLine(f));

        Console.WriteLine("********************");
        
        foreach(string f in fruits) {
        
            Console.WriteLine(f);
        }
        
        Console.WriteLine("********************");
        
        for (int i = 0; i < fruits.Count; i++) {
        
            Console.WriteLine(fruits[i]);
        }
        
    }
}

Output:

banana
mango
apple
watermelon
********************
banana
mango
apple
watermelon
********************
banana
mango
apple
watermelon

C# loop List of integers example

using System;
using System.Collections.Generic;

public class ListDemo
{
    public static void Main(string[] args)
    {
        var nums = new List<int> {10, 20, 30, 40, 50};
        
        nums.ForEach(e => Console.WriteLine(e));
        
        Console.WriteLine("********************");
        
        foreach(int e in nums) {
        
            Console.WriteLine(e);
        }
        
        Console.WriteLine("********************");
        
        for (int i = 0; i < nums.Count; i++) {
        
            Console.WriteLine(nums[i]);
        }
        
    }
}

Output:

10
20
30
40
50
********************
10
20
30
40
50
********************
10
20
30
40
50

Comments