C# List<T>

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

Example #1

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

snippet
using System;
using System.Collections.Generic;

public class ListExample
{
    public static void Main(string[] args)
    {
        // Create a list of strings
        var names = new List();
        names.Add("Sonoo Jaiswal");
        names.Add("Ankit");
        names.Add("Peter");
        names.Add("Irfan");

        // Iterate list element using foreach loop
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}
Output
Sonoo Jaiswal Ankit Peter Irfan
Example #2

Example using collection initializer

snippet
using System;
using System.Collections.Generic;

public class ListExample
{
    public static void Main(string[] args)
    {
        // Create a list of strings using collection initializer
        var names = new List() {"Sonoo", "Vimal", "Ratan", "Love" };
       
        // Iterate through the list.
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}
Output
Sonoo Vimal Ratan Love
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +