HI WELCOME TO Sirees

C# List

Leave a Comment
C# List<T> class is used to store and fetch elements. It can have duplicate elements. It is found in System.Collections.Generic namespace.

C# List<T> example

Let's see an example of generic List<T> 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<T> 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

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.