CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Programming Getting Started With Using Dictionary Collection In C#

Getting Started With Using Dictionary Collection In C#

Rana Ahsan February 12, 2013 2 Comments


 Getting Started With Using Dictionary Collection In C#    

The term ‘Dictionary’ in C# programming, has some other synonyms to refer it such as “associative array”, “key-value pair”, “index-value pair” etc. Dictionary make use of ‘hash table‘ data structure to build up the index/value pair. This is actually 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 basic usage of 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 work with two type 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 dictionary in your application.

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

Dictionary<string, string> myDictionaryData 
                      = new Dictionary<string, string>();

We can define some default initial values at the time of initialization also. The following examples will add two data pair 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"}};

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 parameter in “Add” method on the object. Removing object are done only by the ‘key’ portion. You just need to pass it to object’s “Remove” method. Check the following c# code examples for adding/removing dictionary data pair to 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");

Traverse The Pairs In a Dictionary Object:

There is a single value pair version for 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);
 }

Merge Two Dictionary:

What if we need to merge two different dictionary into a single dictionary object? Yes, we can do so. The following example utilizes C# LinQ Lambda expression technique for merging two different dictionary 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<string, string> 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));

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 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

}

References:

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

Related

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

About Rana Ahsan

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • LinQ Query With Like Operator
  • LinQ To SQL Database Update Operations In C#
  • Get Facebook C# Api Access Token
  • Utilizing Config File In C#.NET Application
  • Control HTML5 Audio With Jquery

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 · Streamline Pro Theme on Genesis Framework · WordPress · Log in