• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Getting Started With Using Dictionary Collection In C#

Getting Started With Using Dictionary Collection In C#

February 12, 2013 by Rana Ahsan 2 Comments

C# Dictionary Tutorials

The term ‘Dictionary’ in C# programming has some other synonyms to refer to it, such as “associative array,” “key-value pair,” “index-value pair,” etc. Dictionary makes use of a ‘hash table’ data structure to build up the index/value pair. This is an extended/advanced array system where you can define the index with other data types than int and set up your data structure in a more meaningful way. In this tutorial, we will look into the basic usage of the C# dictionary class.

Wait! Do you know that, by default Dictionary objects in c# can’t be serialized. Here, besides introduction to c# dictionary class, I will also show you how you can get your dictionary object serialized/deserialized to/from XML as well. Keep reading. Cheers. 😉

Initialize A Dictionary Object In C#:

As Dictionary works with two types of data (one for ‘key’ and one for ‘value’), it requires both these data types to be defined at the time of initialization. Also, the namespace “System.Collections.Generic” is required for using a dictionary in your application.

The following snippet will initialize a simple dictionary with string as both data types:

Dictionary<string, string> myDictionaryData
                      = new Dictionary<string, string>();Code language: HTML, XML (xml)

We can define some default initial values at the time of initialization also. The following examples will add two data pairs in the object at the time of initializing:

Dictionary<string, string> myDictionaryData
                       = new Dictionary<string, string>() {
                         {"testDictionaryIndex1","Test Dictionary Data Value 1"},
                         {"testDictionaryIndex2","Test Dictionary Data Value 2"}};Code language: JavaScript (javascript)

Add/Remove Pairs In Dictionary Object:

Insert and remove operations are fairly easy with a dictionary object. For adding a new pair, you will need to pass both key and value as parameters in “Add” method on the object. Removing object are done only by the ‘key’ portion. You just need to pass it to the object’s “Remove” method. Check the following c# code examples for adding/removing dictionary data pair to an object:

//pass both key and value to add new pair
myDictionaryData.Add("test1", "test value 1");

//pass only key to remove a pair
myDictionaryData.Remove("test1");Code language: JavaScript (javascript)

Traverse The Pairs In a Dictionary Object:

There is a single-value pair version for the C# Dictionary class as well. It is ‘KeyValuePair’ class which can hold a single pair. When we perform a traversing with for or foreach loop, then this class variable can be used to hold each pair and process further as necessary.

 foreach (KeyValuePair<string, string> myItem in myDictionaryData)
 {
     // Do the necessary staffs with myItem
     Console.WriteLine(myItem.Key + " : " + myItem.Value);
 }Code language: PHP (php)

Merge Two Dictionary:

What if we need to merge two different dictionaries into a single dictionary object? Yes, we can do so. The following example utilizes C# LinQ Lambda expression technique for merging two different dictionaries into a different third one:

Dictionary<string, string> myDictionaryData1
                             = new Dictionary<string, string>() {
                               {"testDictionary1Index1","Test Dictionary1 Data Value 1"},
                               {"testDictionary1Index2","Test Dictionary1 Data Value 2"}};
Dictionary<string, string> myDictionaryData2
                            = new Dictionary<string, string>() {
                              {"testDictionary2Index1","Test Dictionary2 Data Value 1"},
                              {"testDictionary2Index2","Test Dictionary2 Data Value 2"}};

Dictionary&lt;string, string&gt; mergedDictionary = new Dictionary<string, string>();
myDictionaryData1.ToList().ForEach(x => mergedDictionary.Add(x.Key, x.Value));
myDictionaryData1.ToList().ForEach(x => mergedDictionary.Add(x.Key, x.Value));Code language: JavaScript (javascript)

Implement Serializable Dictionary In C#:

As by default .NET framework doesn’t provide the facility of c# xml serialization for Dictionary objects, we will need to implement it by ourselves. we can do so by implementing “IXMLSerializable” interface. The following custom class should do your work fine:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> :
Dictionary<TKey, TValue>, IXmlSerializable
{

    #region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    /// <summary>
    /// Custom implementation to read xml data and assign into dictionary
    /// </summary>
    /// <param name="reader">XmlReader object to be used</param>
    public void ReadXml(System.Xml.XmlReader reader)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

        bool wasEmpty = reader.IsEmptyElement;
        reader.Read();

        if (wasEmpty)
        {
            return;
        }

        while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
        {

            reader.ReadStartElement("item");
            reader.ReadStartElement("key");
            TKey key = (TKey)keySerializer.Deserialize(reader);
            reader.ReadEndElement();

            reader.ReadStartElement("value");
            TValue value = (TValue)valueSerializer.Deserialize(reader);
            reader.ReadEndElement();

            this.Add(key, value);

            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }

    /// <summary>
    /// Custom implementation to write dictionary into xml file
    /// </summary>
    /// <param name="writer">XmlWriter object to be used</param>;
    public void WriteXml(System.Xml.XmlWriter writer)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

        foreach (TKey key in this.Keys)
        {
            writer.WriteStartElement("item");
            writer.WriteStartElement("key");
            keySerializer.Serialize(writer, key);
            writer.WriteEndElement();

            writer.WriteStartElement("value");
            TValue value = this[key];
            valueSerializer.Serialize(writer, value);
            writer.WriteEndElement();
            writer.WriteEndElement();
        }

    }
    #endregion

}Code language: HTML, XML (xml)

References:

You are welcome to read the official documentation of MSDN for a complete reference of properties/methods/hierarchy details. I hope this basic C# dictionary tutorial will help you to some extent to start working with it. Let me know if you have any issues/questions. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: .net, c#

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. wanie says

    September 23, 2014 at 3:14 am

    if i have transaction in D like this :
    D={a,b,c,d,e};
    1: {a,b,e}
    2: {b,c,d}
    3: {a,b,c,d}

    I wish to put into vertical format like :
    a b c d e
    1 1 2 2 1
    3 2 3 3
    3

    how would i put it into C#? FYI, my dataset I put into sql table….please very much to help!!!!

    Reply
  2. akash says

    January 22, 2016 at 2:21 am

    Dictionary mergedDictionary = new Dictionary();
    myDictionaryData1.ToList().ForEach(x => mergedDictionary.Add(x.Key, x.Value));
    myDictionaryData1.ToList().ForEach(x => mergedDictionary.Add(x.Key, x.Value));

    //above lines in your blog return error you are merging same dictionary . its will return duplicate key error

    it should be

    Dictionary mergedDictionary = new Dictionary();
    myDictionaryData1.ToList().ForEach(x => mergedDictionary.Add(x.Key, x.Value));
    myDictionaryData2.ToList().ForEach(x => mergedDictionary.Add(x.Key, x.Value));

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023