Converting Lists to Arrays in C#:
Let's see the simple program that shows how to convert a list to an array in C#.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a list of integers
List<int> integerList = new List<int> { 1, 2, 3, 4, 5 };
// Converting the list to an array
int[] integerArray = integerList.ToArray();
// Displaying the elements of the array
Console.WriteLine("Converted Array:");
foreach (int num in integerArray)
{
Console.Write(num + " ");
}
}
}
We have created a List<int>
named integerList
with some sample integers. The ToArray()
method is then used to convert the list to an array, and the result is stored in the integerArray
. Finally, we iterated through the array and displayed its elements.
Output:
Converted Array:
1 2 3 4 5
Comments (0)