Do you think IIT Guwahati certified course can help you in your career?
No
A key-value collection is a data storage structure that stores data as a set of unique identifiers, each mapped to a value. This is known as a “key-value pair”. They are typically much more flexible and offer very fast performance for reading and writing data. Dictionary as a data structure helps implement key-value pairings in C#. Let us learn more about this in detail.
C# Dictionary
The Dictionary class in C# is a generic collection of key-value pairs. It is defined in the System.Collections class. The Generic namespace can store any data type in the form of keys and values. Each key must be unique in the collection, using which a value can be accessed. Keys cannot be null, but values can be duplicated or null.
How to create the Dictionary?
The most common constructor used to create dictionaries is
Dictionary<TKey, TValue>()
Where TKey is the data type of the key and TValue is the data type of the value.
Syntax:
//import statement
using System.Collection.Generics;
Dictionary<TKey, TValue>() = new Dictionary<TKey, TValue>();
Here is a simple example of creating dictionaries in C#.
C#
C#
using System; using System.Collections.Generic;
class NewDictionary {
static public void Main () { Dictionary<string, string> countries = new Dictionary<string, string>(); Console.WriteLine(countries); } }
It clears all the key-value pairs in the dictionary.
Remove(key)
It removes the specified key and its corresponding value from the dictionary.
ContainsKey(key)
It checks if a given key exists in the dictionary.
ContainsValue(value)
It checks if a given value exists in the dictionary.
Count
It returns the number of key-value pairs in the dictionary.
Basic Operations of Dictionaries in C#
1. Add or update elements
C#
C#
using System; using System.Collections.Generic;
class NewDictionary{ static public void Main () { Dictionary<string, string> countries = new Dictionary<string, string>(){ {"Australia","Canberra"}, {"Austria","Vienna"} };
// Using Add() method countries.Add("China","Hongkong"); countries.Add("Egypt","Giza");
// Printing key-value pairs foreach(KeyValuePair<string, string> ele in countries) { Console.WriteLine("{0} and {1}",ele.Key, ele.Value); } Console.WriteLine();
// Updating the values of selected keys countries["Egypt"] = "Cairo"; countries["China"] = "Beijing";
foreach(KeyValuePair<string, string> ele1 in countries) { Console.WriteLine("{0} and {1}", ele1.Key, ele1.Value); } } }
Output:
Australia and Canberra
Austria and Vienna
China and Hongkong
Egypt and Giza
Australia and Canberra
Austria and Vienna
China and Beijing
Egypt and Cairo
To retrieve all key-value pairs as objects for traversal.
foreach (KeyValuePair<TKey, TValue> obj in dictionary_name)
Example
C#
C#
using System; using System.Collections.Generic;
class NewDictionary{ static public void Main () { Dictionary<string, string> countries = new Dictionary<string, string>(){ {"Australia","Canberra"}, {"Austria","Vienna"}, {"China","Beijing"} };
// To display value of a key Console.WriteLine("{0} is the capital of Austria\n", countries["Austria"]);
// To display keys foreach (string key in keys) { Console.WriteLine("key: {0}",key); } Console.WriteLine();
foreach(KeyValuePair<string, string> ele in countries) { Console.WriteLine("{0} and {1}", ele.Key, ele.Value); } } }
Output:
Vienna is the capital of Austria
key: Australia
key: Austria
key: China
Australia and Canberra
Austria and Vienna
China and Beijing
3. Remove elements.
C#
C#
using System; using System.Collections.Generic;
class NewDictionary{ static public void Main () { Dictionary<string, string> countries = new Dictionary<string, string>(){ {"Australia","Canberra"}, {"Austria","Vienna"}, {"China","Beijing"} };
// To display number of key-value pairs Console.WriteLine("Initial dictionary count: {0}", countries.Count);
foreach(KeyValuePair<string, string> ele in countries) { Console.WriteLine("{0} and {1}", ele.Key, ele.Value); }
// Removing elements countries.Remove("Austria"); countries.Remove("Australia");
Console.WriteLine("\nAfter removing Austria and Australia: {0}", countries.Count);
foreach(KeyValuePair<string, string> ele in countries) { Console.WriteLine("{0} and {1}", ele.Key, ele.Value); }
//clears entire dictionary countries.Clear(); } }
Output:
Initial dictionary count: 3
Australia and Canberra
Austria and Vienna
China and Beijing
After removing Austria and Australia: 1
China and Beijing
Frequently Asked Questions
What is dictionary of classes in C#?
A dictionary of classes in C# is a collection that associates unique keys with objects of a specific class type. It allows efficient retrieval and manipulation of objects based on their unique keys, providing a way to organize and access class instances in memory.
What is the difference between dictionary and Hashtable in C#?
The main difference lies in their implementation. While both store key-value pairs, a dictionary is a generic collection introduced in .NET Framework 2.0, offering type safety and better performance. Hashtable, on the other hand, is not type-safe and relies on boxing and unboxing, leading to potential performance overhead.
What is faster than dictionary in C#?
For scenarios requiring fast key-based lookups and memory efficiency, SortedDictionary or SortedList can be faster than Dictionary in C#. They maintain sorted order based on keys, offering efficient retrieval but may have slower insertion and deletion operations compared to Dictionary.
What is the difference between array and dictionary in C#?
An array in C# is a fixed-size collection of elements of the same data type, accessed using an index. In contrast, a dictionary is a dynamic collection that stores key-value pairs, allowing efficient retrieval of values based on unique keys. Arrays are indexed by integer values, while dictionaries are indexed by keys.
When to use dictionary in C#?
Use a dictionary in C# when you need to associate unique keys with values and require fast lookup operations based on those keys. It's particularly useful for scenarios involving data indexing, caching, or maintaining mappings between objects.
Conclusion
This article extensively discusses Dictionaries in C#. They play a crucial role in organizing and accessing data efficiently. They provide a powerful tool for associating unique keys with values, facilitating fast lookup operations and enabling various data manipulation tasks.