How to iterate over a C# list?


Declare a list and add elements −

var products = new List < string > ();

// adding elements
products.Add("Belts");
products.Add("T-Shirt");
products.Add("Trousers");

Use a loop to iterate −

foreach(var p in products) {
   Console.WriteLine(p);
}

Example

Let us see the complete example −

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(string[] args) {
      var products = new List < string > ();
      products.Add("Belts");
      products.Add("T-Shirt");
      products.Add("Trousers");

      Console.WriteLine("Our list....");
      foreach(var p in products) {
         Console.WriteLine(p);
      }
   }
}

Updated on: 02-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements