Introduction
Here is the code that converts a List to an array in C#.
This example creates a new List and populates it with some integers. The List is a constructed type and can only hold integer values. Next, it uses ToArray on the List.
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
//creation of list<>
List<int> number = new List<int>();
//add the elements in the list
number.Add(10);
number.Add(20);
number.Add(15);
number.Add(25);
number.Add(30);
number.Add(35);
number.Add(40);
number.Add(45);
//creation of an array
int[] a = number.ToArray();
//display the array element
Console.WriteLine("the array elements are:");
foreach (int i in a)
{
Console.WriteLine(i);
}
}
}
}
Output
Convert Array to List
In this example, we see how to convert an array of any number of elements to a List that has the same type of elements. First, I initialize a new string[] array containing seven strings. Next, it converts the collection to a List with the new List constructor.
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
//create array
string[] s = new string[] { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" };
//create list
List<string> days = new List<string>(s);
Console.WriteLine("The list element is:");
foreach (string i in days)
{
Console.WriteLine(i);
}
}
}
}
Output
Find maximum element
Write the following code to find the maximum element in the List. For this, we use the max() method of the List.
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
List<int> a = new List<int>();
a.Add(10);
a.Add(20);
a.Add(1);
a.Add(30);
a.Add(67);
Console.WriteLine("list elements are:");
foreach (int i in a)
{
Console.WriteLine(i);
}
int max = a.Max();
Console.WriteLine("Maximum element in the list is:" + max);
}
}
}
Output
Find minimum element
Write the following code to find the minimum element in the List. For this, we use the min() method of the List.
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
List<int> a = new List<int>();
a.Add(10);
a.Add(20);
a.Add(1);
a.Add(30);
a.Add(67);
Console.WriteLine("list elements are:");
foreach (int i in a)
{
Console.WriteLine(i);
}
int min = a.Min();
Console.WriteLine("Minimum element in the list is:" + min);
}
}
}
Output
Summary
In this article, I explain how to convert the array into a list and a list into an array and also to find the maximum and minimum number from the List.