C Sharp List

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# List

C# List class is used to store and fetch elements. It can have duplicate elements. It is found in System.Collections.Generic namespace.

C# List example

Let's see an example of generic List class that stores elements using Add() method and iterates the list using for-each loop.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class ListExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         // Create a list of strings  
  9.         var names = new List<string>();  
  10.         names.Add("Sonoo Jaiswal");  
  11.         names.Add("Ankit");  
  12.         names.Add("Peter");  
  13.         names.Add("Irfan");  
  14.   
  15.         // Iterate list element using foreach loop  
  16.         foreach (var name in names)  
  17.         {  
  18.             Console.WriteLine(name);  
  19.         }  
  20.     }  
  21. }  

Output:

Sonoo Jaiswal
Ankit
Peter
Irfan

C# List example using collection initializer

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class ListExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         // Create a list of strings using collection initializer  
  9.         var names = new List<string>() {"Sonoo""Vimal""Ratan""Love" };  
  10.          
  11.         // Iterate through the list.  
  12.         foreach (var name in names)  
  13.         {  
  14.             Console.WriteLine(name);  
  15.         }  
  16.     }  
  17. }  

Output:

Sonoo
Vimal
Ratan
Love