
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<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));
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 🙂
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!!!!
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));