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
Comments (0)