
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. The dictionary uses 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 more meaningfully. This tutorial 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#:
The dictionary works with two types of data (one for ‘key’ and one for ‘value’) and requires both to be defined at the time of initialization. Also, the namespace “System.Collections.Generic” is required to use 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 also define some default initial values at the time of initialization. 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. To add a new pair, you must pass both key and value as parameters in the “Add” method on the object. Removing objects is done only by the ‘key’ portion. You just need to pass it using 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 also a single-value pair version for the C# Dictionary class. It is the ‘KeyValuePair’ class, which can hold a single pair. When we perform a traversing with for or foreach loop, this class variable can 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 merge two different dictionaries into a single dictionary object? Yes, we can do so. The following example utilizes the 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#:
By default, the .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 the “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 start working with it to some extent. Let me know if you have any issues/questions. Happy coding 🙂
Discover more from CODESAMPLEZ.COM
Subscribe to get the latest posts sent to your email.
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));