How to iterate over a C# list?

CsharpProgrammingServer Side Programming

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);
      }
   }
}
raja
Published on 31-Aug-2018 09:17:38
Advertisements