C# – Create List from Array

In C#, array is a collection of elements that belong to basic/strong datatypes. List can contain elements belonging to more generic datatype, unlike an array.

In this tutorial, we shall learn how to create a C# List from an Array.

To create a List from Array, pass the array to the List constructor while creating a new List. Also, please note that the datatype of elements in the list should match the datatype of elements in the array.

Example 1 – Create C# List from Array

In this example, we have an array of integers numbers. We shall create a list nums using array numbers. As the array contains elements of type integer, you can create a list of integers only.

Program.cs

</>
Copy
using System;
using System.Collections.Generic;

class Program {
    static void Main(string[] args) {
        //array
        int[] numbers = {10, 20, 30, 40};
        //create list from array
        List<int> nums = new List<int>(numbers);
        
        //print list
        foreach (int num in nums) {
            Console.WriteLine(num);
        }
    }
}

Run the above C# program. Now the new list contains all the elements of the array.

Output

10
20
30
40

Example 2 – Create C# List from String Array

In this example, we shall create List of Strings from an Array of Strings. As already mentioned, datatypes of elements in array and list has to match.

Program.cs

</>
Copy
using System;
using System.Collections.Generic;

class Program {
    static void Main(string[] args) {
        //array
        string[] numbers = {"One", "Two", "Three"};
        //create list from array
        List<string> nums = new List<string>(numbers);
        
        //print list
        foreach (string num in nums) {
            Console.WriteLine(num);
        }
    }
}

Run the above C# program.

Output

One
Two
Three

Conclusion

In this C# Tutorial, we learned how to create a list from a given array.