c# - How to create a Dictionary from a list

Dictionary from list
dictionary-from-list.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  
    
<!DOCTYPE html>      
<script runat="server">    
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //initialize a new generic list of keyvaluepair.
        List<KeyValuePair<int, string>> birdsList = new List<KeyValuePair<int, string>>();
        
        //create new keyvaluepair.
        KeyValuePair<int, string> bird1 = new KeyValuePair<int, string>(1, "Canada Goose");
        KeyValuePair<int, string> bird2 = new KeyValuePair<int, string>(2, "Cackling Goose");
        KeyValuePair<int, string> bird3 = new KeyValuePair<int, string>(3, "Egyptian Goose");
        
        //add keyvaluepair to lsit
        birdsList.Add(bird1);
        birdsList.Add(bird2);
        birdsList.Add(bird3);

        Label1.Text = "generic list elements..........";
        foreach (KeyValuePair<int, string> pair in birdsList)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //create a dictionary from generic list.  
        Dictionary<int, string> birds = birdsList.ToDictionary(x=>x.Key,x=>x.Value);

        Label1.Text += "<br /><br />dictionary elements..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }
    }      
</script>      
      
<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>c# example - dictionary from list</title>      
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            c# example - dictionary from list
        </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="dictionary from list"      
            OnClick="Button1_Click"    
            Height="40"      
            Font-Bold="true"      
            />      
    </div>      
    </form>      
</body>      
</html>
More c# examples