List to array c#

array to list
In this post we will se how to convert list to array.We need to convert list to array many times in C# programming. Converting list to array can be done by various ways. We are going to see C# examples to convert the list to array.

we will see the way to convert list to an array. we use .ToArray() parameter less instance method that converts list to an array. Below example shows how list get converted in to array using .ToArray() method:

Example to convert list to array [C#]

using System;
using System.Collections.Generic;

class Program
{
 static void Main()
 {
  // List to convert into Array.
  List<string> lstString = new List<string>();
  lstString.Add("Convert");
  lstString.Add("List");
  lstString.Add("TO");
  lstString.Add("Array");
  // use .ToArray() Method to convert list to array
  string[] strArray = lstString.ToArray();
 }
}

Array to List [C#]

convert array to list

Some times we need add elements of an array to list in C# programming. We can use .Add() method of List class to add array elements to the List.Using . we also can use .Add() method to while converting array to List.

We will see example that will show how used .Add method to convert array to List. Here we iterate through array elements and then one by one we add those elements to List.



using System.Collections.Generic; 

protected void Button1_Click(object sender, EventArgs e) 
{     
 string[] arrStr = { "Add", "Array", "Elements", "To", "List", "C#" };      
 List <string> strList = new List<string>();     
 foreach (string stritem in arrStr)    
 {          
  lstString.Add(stritem);    
 }      
}