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