c# - How to convert Dictionary values into array

How to convert Dictionary values into array
.Net framework dictionary represents a collection of keys and values. Dictionary<TKey, TValue>.Values property allow us to get a collection containing the values in the Dictionary<TKey, TValue>. this dictionary 'Values' property exists in System.Collections.Generic namespace. the 'Values' property value type is System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection.

so the dictionary 'Values' property allow us to get a generic list (collection) of dictionary values. to convert dictionary values into array, we can convert this generic list by its built in method ToArray(). List<T>.ToArray() method allow us to copy the elements of the List<T> to a new array. finally the conversion process is Dictionary<TKey, TValue>.Values.ToArray().

the following asp.net c# example code demonstrate us how can we convert dictionary values to an array programmatically at run time in an asp.net application.
ConvertDictionaryValuesIntoArray.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Collections.Generic" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Dictionary<string, string> colors = new Dictionary<string, string>();
        colors.Add("DarkSlateBlue", "#483D8B");
        colors.Add("DeepPink", "#FF1493");
        colors.Add("FireBrick", "#B22222");
        colors.Add("ForestGreen", "#228B22");

        Label1.Text = "Dictionary Keys | Values.....<br />";
        foreach(KeyValuePair<string,string> pair in colors)
        {
            Label1.Text += pair.Key +" | "+ pair.Value + "<br />";
        }

        string[] colorArray = colors.Values.ToArray();
        Label1.Text += "<br />Color Array Items....";
        foreach (string color in colorArray)
        {
            Label1.Text += "<br />" + color;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to convert Dictionary values into array</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy; font-style:italic;">
            System.Collections.Generic.Dictionary
            <br /> How to convert Dictionary values into array
        </h2>
        <hr width="450" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="SeaGreen"
             Font-Names="Courier New"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Convert Dictionary values into array"
            Height="45"
            Font-Bold="true"
            ForeColor="Navy"
            />
    </div>
    </form>
</body>
</html>
More c# examples