Generic List ToArray() Method
.Net framework generic list ToArray() method allow us to copy the elements of the List<T> to a new array.
the List class ToArray() method exists in System.Collections.Generic namespace. this method has no required or optional parameter.
the ToArray() method return value type is T[] that represents an array containing copies of the elements of the generic List<T>. the ToArray() method copies list elements using Array.Copy.
the following asp.net c# example code demonstrate us how can we copy the list elements to a new array programmatically at run time in an asp.net application.
the ToArray() method return value type is T[] that represents an array containing copies of the elements of the generic List<T>. the ToArray() method copies list elements using Array.Copy.
the following asp.net c# example code demonstrate us how can we copy the list elements to a new array programmatically at run time in an asp.net application.
GenericListToArrayMethod.aspx
<%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
List<string> colors = new List<string>() {"Navy","OldLace","PaleGreen"};
colors.Add("PaleVioletRed");
colors.Add("PeachPuff");
Label1.Text = "List Elements....<br />";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
string[] colorArray = colors.ToArray();
Label1.Text += "<br /><br />After Call ToArray() Method Array Elements are.....<br />";
for (int i = 0; i < colorArray.Length; i++ )
{
Label1.Text += "<br />" + colorArray[i];
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Generic List ToArray() - How to copy the elements of the List to a new array</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:SlateBlue; font-style:italic;">
System.Collections.Generic.List ToArray() Method
<br /> How to copy the elements of the List to a new array
</h2>
<hr width="550" align="left" color="Purple" />
<asp:Label
ID="Label1"
runat="server"
ForeColor="OliveDrab"
Font-Size="Large"
Font-Names="Courier New"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Generic List ToArray() Method"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>
