How to Store an Array in a List in C#?

How to Store an Array in a List in C#?
 
Lists in C# are very easy and efficient way to store data as these can be resized dynamically. With List, you do not need to manage the size on your own. Lists are generics and constructed types. You need to use < and > in the List declaration. Lists can handle any kind of element type. You can perform variety of operations on list with ease.
 
In this article we will see how can we store an array into a list and access it.
 
Lets have a look at very simple example of List
 
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       List list = new List();
       list.Add(1);
       list.Add(2);
       list.Add(3);
       list.Add(4);
    }
}
 
Now lets see how can we store an entire array into the list? I wll use AddRange function to copy an array into the list.
 
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        List a = new List();
        a.Add(1);
        a.Add(2);
        a.Add(3);
        a.Add(4);
        int[] b = new int[3];
        b[0] = 5;
        b[1] = 6;
        b[2] = 7;
        a.AddRange(b);
        foreach (int i in a)
        {
           Console.WriteLine(i);
        }
    }
}
 
Output
1
2
3
4
5
6
7
 
Now, 2nd way to copy an entire array into the list. I will not use AddRange function here. I will just directly pass array while declaring the list.
 
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       int[] arr = new int[3];
       arr[0] = 1;
       arr[1] = 2;
       arr[2] = 3;
       List list = new List(arr);
       Console.WriteLine(list.Count);      
    }
}
 
Output
3
 
C# Program to convert a list into an array. I will use Join function to join all the elements which are converted into array with comma.
 
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       List cities = new List();
       cities.Add("New York");
       cities.Add("Paris");
       cities.Add("London");
       cities.Add("Berlin");
       // Join strings into one CSV line
       string line = string.Join(",", cities.ToArray());
      Console.WriteLine(line);
    }
}
 
Output
New York,Paris,London,Berlin
 
C# Program to access elements of the list. There are two ways to access the elements of the list

1. By using foreach
2. By using Count property of the list
 
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
      List list = new List();
      list.Add(1);
      list.Add(2);
      list.Add(3);
      foreach (int prime in list)
      {
         Console.WriteLine(prime);
      }
      for (int i = 0; i < list.Count; i++)
      {
         Console.WriteLine(list[i]);
      }
    }
}