c# - How to convert a Dictionary to a string

Dictionary to string
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 structure 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 convert a Dictionary object to a String object. To achieve this, we initially initialize an instance of an empty Dictionary object. Whose key and value data types both are String. Then we add elements (key-value pair) to the Dictionary instance. We can display the Dictionary elements on the screen (ap.net page) using a foreach loop.

We initialize an empty StringBuilder object. StringBuilder object represents a mutable string of characters. We can add text to the StringBuilder using its Append() method. So we loop through the Dictionary elements and append its keys and values to the StringBuilder. Finally, we convert the StringBuilder to a String object using the ToString() method. The converted String object holds the Dictionary elements keys and values text.

<%@ 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>() {  
            {1,"White Stork"},  
            {3,"Marabou Stork"},  
            {4,"Scarlet Ibis"}  

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

        //create a stringbuilder.
        StringBuilder sb = new StringBuilder();
        //append dictionary key value to stringbuilder.
        foreach (KeyValuePair<int, string> pair in birds)

        Label1.Text += "<br /><br />dictionary elements to string.....<br />";
        Label1.Text += sb.ToString().TrimEnd(',');
<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>c# example - dictionary to string</title>      
    <form id="form1" runat="server">      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            c# example - dictionary to string
        <hr width="550" align="left" color="Gainsboro" />      
        <br /><br />    
            Text="dictionary to string"      
More c# examples