TechieClues TechieClues
Updated date Feb 14, 2023
In this blog, we will learn how to convert an array to a list in C#

We can easily convert an array to a list using the below methods in C#. Let us see the methods, 

  • Using List Constructor
  • Using ToList() method

Using List Constructor

The list constructor is used to convert an array into a list using List<T>() constructor which accepts IEnumerable<T> as an argument. In the below example, we initialize a new instance of the List<T> class which copies the elements from the cars collection.

using System;
using System.Collections.Generic;

namespace ConvertArrayToList
{
    class Program
    {
        static void Main()
        {
            // Cars array
            string[] cars = { "Mazda", "Toyota", "Audi", "Benz", "Skoda" };
            
            // List of cars
            List<string> listOfCars = new List<string>(cars);

            // Print cars
            foreach (var car in listOfCars)
                Console.WriteLine(car);

            Console.ReadKey();
        }
    }
}

Output:

Mazda
Toyota
Audi
Benz
Skoda

Using ToList() method

The easiest way in C# to convert an array into a list is using ToList() method. In the below example, we use the ToList() method which converts an array of elements into a  that a List<T>.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConvertArrayToList
{
    class Program
    {
        static void Main()
        {
            // Cars array
            string[] cars = { "BMW", "Audi", "Ferrari", "Rolls Royce", "Honda" };
            
            // List of cars
            List<string> listOfCars = cars.ToList();

            // Print cars
            foreach (var car in listOfCars)
                Console.WriteLine(car);

            Console.ReadKey();
        }
    }
}

Output:

BMW
Audi
Ferrari
Rolls Royce
Honda

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!