C Sharp List

C# List<T>

To store and to fetch the elements, the C# List<T> class is used which is found in the System.Collections.Generic namespace. The C# List<T> class can also store duplicate elements.

Example:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        // Create a list of strings  
        var countries = new List<string>();  
        countries.Add("India");  
        countries.Add("Australia");  
        countries.Add("Japan");  
        countries.Add("Canada");  
        countries.Add("Mexico");  
 
        // Iterate list element using foreach loop  
        foreach (var country in countries)  
        {  
            Console.WriteLine(country);  
        }  
    }  
}

Output:

Explanation:

In the above example, we are using the generic List<T> class. It uses the Add() method to store the elements and the for-each loop to iterate the list.

Example:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        // Create a list of strings using collection initializer  
        var countries = new List<string>() {"India", "Australia", "Canada", "Mexico", "Japan" };  
 
        // Iterate through the list.  
        foreach (var country in countries)  
        {  
            Console.WriteLine(country);  
        }  
    }  
}

Output:

Explanation:

In the above example, we are using the generic List<T> class to create a list of strings using the collection initializer.

 

Please follow and like us:
Content Protection by DMCA.com