c# - How to get first key value from Dictionary

Dictionary get first key value
The Dictionary class represents a collection of keys and values. .Net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can get the first key and value from a Dictionary. The .net frameworks have the built-in method to get the first key-value pair from a Dictionary instance. So the .net c# developers can easily get the first key-value pair from a Dictionary items collection.

The Enumerable First() method returns the first element of a sequence. The First() method throws InvalidOperationException if the source sequence is empty. And the Enumerable FirstOrDefault() method returns the first element of a sequence, or a default value if no element is found.

So, we can get the Dictionary’s first key-value pair using Enumerable First() and FirstOrDefault() methods. From the key-value pair, we can extract the key and value from it. In this tutorial, we get the Dictionary’s first key-value pair using the Enumerable FirstOrDefault() method.

<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {10,"Black Guillemot"},
            {20,"Rhinoceros Auklet"},
            {30,"Crowned Sandgrouse"},
            {40,"Speckled Pigeon"},
            {50,"Eurasian Collared Dove"}

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;

        //get first keyvaluepair from dictionary.
        KeyValuePair<int, string> firstPairOfDictionary = birds.FirstOrDefault();

        Label1.Text += "<br /><br />dictionary first key value.........<br />";
        Label1.Text += firstPairOfDictionary.Key + " ........ " + firstPairOfDictionary.Value;
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary get first key value</title>    
    <form id="form1" runat="server">    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary get first key value
        <hr width="550" align="left" color="Gainsboro" />    
        <br /><br />  
            Text="dictionary get first key value"    
More c# examples