The dictionary collection represents Key-Value pairs. It is similar to an English dictionary with different words and their meanings. The dictionary collection is included in the System.Collections.Generic namespace.
The different constructors and their description is given as follows:
Table: Constructors in Dictionary Collection in C#
Source: MSDN
Constructors | Description |
---|---|
Dictionary<TKey,TValue>() | This constructor initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type. |
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) | This constructor initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the default equality comparer for the key type. |
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) | This constructor initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the specified IEqualityComparer<T> |
Dictionary<TKey,TValue>(IEqualityComparer<TKey>) | This constructor initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the specified IEqualityComparer<T>. |
Dictionary<TKey,TValue>(Int32) | This constructor initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the default equality comparer for the key type. |
Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) | This constructor initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer<T>. |
Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) | This constructor initializes a new instance of the Dictionary<TKey,TValue> class with serialized data. |
The different properties and their description is given as follows:
Table: Properties in Dictionary Collection in C#
Source: MSDN
Properties | Description |
---|---|
Comparer | This property gets the IEqualityComparer<T> that is used to determine equality of keys for the dictionary. |
Count | This property gets the number of key/value pairs contained in the Dictionary<TKey,TValue>. |
Item[TKey] | This property gets or sets the value associated with the specified key |
Item[TKey] | This property gets a collection containing the keys in the Dictionary<TKey,TValue>. |
Values | This property gets a collection containing the values in the Dictionary<TKey,TValue>. |
The different methods and their description is given as follows:
Table: Methods in Dictionary Collection in C#
Source: MSDN
Methods | Description |
---|---|
Add(TKey, TValue) | This method adds the specified key and value to the dictionary. |
Clear() | This method removes all keys and values from the Dictionary<TKey,TValue>. |
ContainsKey(TKey) | This method determines whether the Dictionary<TKey,TValue> contains the specified key. |
ContainsValue(TValue) | This method determines whether the Dictionary<TKey,TValue> contains a specific value. |
Equals(Object) | This method determines whether the specified object is equal to the current object. |
GetEnumerator() | This method returns an enumerator that iterates through the Dictionary<TKey,TValue> |
GetHashCode() | This method serves as the default hash function. |
GetObjectData(SerializationInfo, StreamingContext) | This method implements the ISerializable interface and returns the data needed to serialize the Dictionary<TKey,TValue> instance. |
GetType() | This method gets the Type of the current instance. |
MemberwiseClone() | This method creates a shallow copy of the current Object. |
OnDeserialization(Object) | This method implements the ISerializable interface and raises the deserialization event when the deserialization is complete. |
Remove(TKey) | This method removes the value with the specified key from the Dictionary<TKey,TValue>. |
ToString() | This method returns a string that represents the current object. |
TryGetValue(TKey, TValue | This method gets the value associated with the specified key. |
Some of the Dictionary operations are given as follows:
Elements can be added to the dictionary using the Add() method. It adds the specified key and value pairs to the dictionary. The program that demonstrates this is given as follows:
Source Code: Program to add elements in Dictionary in C#
using System; using System.Collections.Generic; namespace DictionaryDemo { class Example { static void Main(string[] args) { Dictionary<int, string> d = new Dictionary<int, string>(); d.Add(1,"Harry"); d.Add(2,"Sally"); d.Add(3,"Clarke"); d.Add(4,"James"); d.Add(5,"Emma"); d.Add(6,"Susan"); Console.WriteLine("Dictionary elements are as follows:"); foreach (KeyValuePair<int, string> i in d) { Console.WriteLine("Key: {0} Value: {1}", i.Key, i.Value); } } } }
The output of the above program is given below:
Dictionary elements are as follows: Key: 1 Value: Harry Key: 2 Value: Sally Key: 3 Value: Clarke Key: 4 Value: James Key: 5 Value: Emma Key: 6 Value: Susan
An element can be deleted from the Dictionary using the Remove() method. This method deletes the key, value pair with the specific key that is provided. The program that demonstrates this is given as follows:
Source Code: Program to delete elements from Dictionary in C#
using System; using System.Collections.Generic; namespace DictionaryDemo { class Example { static void Main(string[] args) { Dictionary<int, string> d = new Dictionary<int, string>(); d.Add(1,"Harry"); d.Add(2,"Sally"); d.Add(3,"Clarke"); d.Add(4,"James"); d.Add(5,"Emma"); d.Add(6,"Susan"); Console.WriteLine("Original dictionary elements:"); foreach (KeyValuePair<int, string> i in d) { Console.WriteLine("Key: {0} Value: {1}", i.Key, i.Value); } d.Remove(3); d.Remove(6); Console.WriteLine("Dictionary elements after deletion:"); foreach (KeyValuePair<int, string> i in d) { Console.WriteLine("Key: {0} Value: {1}", i.Key, i.Value); } } } }
The output of the above program is given below:
Original dictionary elements: Key: 1 Value: Harry Key: 2 Value: Sally Key: 3 Value: Clarke Key: 4 Value: James Key: 5 Value: Emma Key: 6 Value: Susan Dictionary elements after deletion: Key: 1 Value: Harry Key: 2 Value: Sally Key: 4 Value: James Key: 5 Value: Emma
The ContainsKey() method finds if a key is present in the Dictionary or not. If it is present, ContainsKey() returns TRUE and otherwise it returns FALSE. Similarly, ContainsValue() finds if a value is present in the Dictionary or not. If it is present, ContainsValue() returns TRUE and otherwise it returns FALSE.
The program that demonstrates this is given as follows:
Source Code: Program to find an element in Dictionary in C#
using System; using System.Collections.Generic; namespace DictionaryDemo { class Example { static void Main(string[] args) { Dictionary<int, string> d = new Dictionary<int, string>(); d.Add(1,"Harry"); d.Add(2,"Sally"); d.Add(3,"Clarke"); d.Add(4,"James"); d.Add(5,"Emma"); d.Add(6,"Susan"); Console.WriteLine("Dictionary elements:"); foreach (KeyValuePair<int, string> i in d) { Console.WriteLine("Key: {0} Value: {1}", i.Key, i.Value); } Console.WriteLine(); Console.WriteLine("The key 3 is present in Dictionary: " + d.ContainsKey(3)); Console.WriteLine("The value Lucy is present in Dictionary: " + d.ContainsValue("Lucy")); } } }
The output of the above program is given below:
Dictionary elements: Key: 1 Value: Harry Key: 2 Value: Sally Key: 3 Value: Clarke Key: 4 Value: James Key: 5 Value: Emma Key: 6 Value: Susan The key 3 is present in Dictionary: True The value Lucy is present in Linked List: False
Use the Clear() method to initialize a dictionary to an empty dictionary. Let us see an example:
Source Code: Program to initialize a dictionary to an empty dictionary in C#
using System; using System.Collections.Generic; using System.Linq; namespace Example { public class Demo { public static void Main(string[] args) { var d = new Dictionary < string,string > (); d.Clear(); if (d.Count == 0) { Console.WriteLine("Empty..."); } } } }
The above example gives the following output:
Empty...
To iterate over a C# Dictionary, you can consider using another collection i.e. List. Let us see how to implement it:
Source Code: Program to iterate over a C# Dictionary in C#
using System; using System.Collections.Generic; public class Example { public static void Main() { IDictionary < int, int > dict = new Dictionary < int, int > (); dict.Add(1, 189); dict.Add(2, 145); dict.Add(3, 178); dict.Add(4, 199); dict.Add(5, 123); dict.Add(6, 156); dict.Add(7, 166); dict.Add(8, 185); List < int > l = new List < int > (dict.Keys); foreach(int res in l) { Console.WriteLine("{0}, {1}", res, dict[res]); } } }
The above program gives the following output:
1, 189 2, 145 3, 178 4, 199 5, 123 6, 156 7, 166 8, 185
Source Code: Program to get the list of keys from a Dictionary in C#
using System; using System.Collections.Generic; public class Demo { public static void Main() { Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "One"); dict.Add(2, "Two"); dict.Add(3, "Three"); dict.Add(4, "Four"); dict.Add(5, "Five"); List<int> k = new List<int>(dict.Keys); foreach (int keys in k) { Console.WriteLine(keys); } } }
The above program gives the following output:
1 2 3 4 5
To convert a collection into Dictionary, use the ToDictionary() method as shown in the below example:
Source Code: Program to convert a collection into Dictionary in C#
using System; using System.Linq; using System.Collections.Generic; class Example { static void Main() { string[] s = new string[] {"Chair", "Table"}; var dict = s.ToDictionary(i => i, i => true); foreach (var res in dict) { Console.WriteLine("{0}, {1}", res.Key, res.Value); } } }
In the above example, the following is the output:
Chair, True Table, True
To combine Dictionary, use another C# Collections i.e. HashSet. With that, implement the UnionsWith() method.
Let us see an example:
Source Code: Program to combine Dictionary of two keys in C#
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary < string, int > d1 = new Dictionary < string, int > (); d1.Add("AB", 1); d1.Add("BC", 2); d1.Add("CD", 3); d1.Add("EF", 4); d1.Add("GH", 5); d1.Add("IJ", 6); Dictionary < string, int > d2 = new Dictionary < string, int > (); d2.Add("KL", 7); d2.Add("MN", 8); d2.Add("OP", 9); d2.Add("QR", 10); HashSet < string > h = new HashSet < string > (d1.Keys); h.UnionWith(d2.Keys); foreach(string res in h) { Console.WriteLine(res); } } }
The above program gives the following output:
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary < string, int > d1 = new Dictionary < string, int > (); d1.Add("AB", 1); d1.Add("BC", 2); d1.Add("CD", 3); d1.Add("EF", 4); d1.Add("GH", 5); d1.Add("IJ", 6); Dictionary < string, int > d2 = new Dictionary < string, int > (); d2.Add("KL", 7); d2.Add("MN", 8); d2.Add("OP", 9); d2.Add("QR", 10); HashSet < string > h = new HashSet < string > (d1.Keys); h.UnionWith(d2.Keys); foreach(string res in h) { Console.WriteLine(res); } }
Avery good write-up. Please let me know what are the types of C# libraries used for AI development.
very satisfied!!
Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).
Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz
The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation
Leave a Reply
Your email address will not be published. Required fields are marked *