c# - How to convert a delimited string to a dictionary

String to dictionary
string-to-dictionary.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>
  
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //this section create a string variable.    
        string txt = "1 Shoveler. 2 Pintail. 3 Duck. 4 Penguin";

        Label1.Text = "string of birds value..................<br />";
        Label1.Text += txt;

        //this line create a new array from string using string split.
        string[] array = txt.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries).ToArray();

        //this line create a new dictionary object.
        Dictionary<int, string> dc = new Dictionary<int, string>();

        foreach (string s in array)
        {
            //create new array from string
            string[] array2 = s.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
            
            //add new keyvaluepair to dictionary.
            dc.Add(Convert.ToInt32(array2[0]), array2[1]);
        }

        Label1.Text += "<br /><br />dictionary keys and values..........";
        foreach (KeyValuePair<int, string> kvp in dc)
        {
            Label1.Text += "<br />Key: " + kvp.Key + " Value: " + kvp.Value;
        }
    }    
</script>    
    
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - string to dictionary</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - string to dictionary
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="string to dictionary"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>
More c# examples