Dictionary is a collection object just like list object; in dictionary object, we can store values with key value pair, in this tutorial you will learn how to use C# Dictionary class with examples
C# Dictionary, initialize Dictionary ObjectIDictionary<int, string> _dictObj = new Dictionary<int, string>();
Here you learn C# Dictionary , IDictionary today, to access this object you need use the namespace System.Collections.Generic
C# Dictionary has no different meaning than English Dictionary word, it has exact same meaning, In C# Dictionary we can store information with key, value combination, and retrieve the value using the key.
Before we see some C# Dictionary Example, let’s look at some of the Important Properties
Some commonly used dictionary methods.
Add key-value pairs <TKey, TValue>
in Dictionary collection.
Adds an item with a key and value into the Dictionary.
Returns true and specified key assigns value in (out) parameter, if key does not exists then return false.
Suppose we are trying to find index 4 in above dictionary object using TryGetValue method
string _valueResult; if (_dictObj.TryGetValue(4, out _valueResult)) { Console.WriteLine(_valueResult); } else { Console.WriteLine("Specified key not found."); }
Checks whether the specified key (integer) exists in Dictionary object collection
Checks whether the specified KeyValuePair exists in Dictionary <TKey, TValue>
Note: While adding in Dictionary object, you cannot add duplicate or null keys in Dictionary C#, though values can be duplicated or set as null, but Keys must be unique otherwise it will throw runtime exception.
using System.Collections.Generic; IDictionary<int, string> _dictObj = new Dictionary<int, string>(); _dictObj.Add(1, "C# Dictionary Example"); _dictObj.Add(2, "Learning C# .Net"); _dictObj.Add(3, "Learning SQL Database"); _dictObj.Add(4, "Learning ASP.Net");
Two ways you can retrieve value from Dictionary object.
Console.WriteLine(_dictObj[1]);
If the specified key does not exist then it will throw KeyNotFoundException.
for (int i = 0; i < _dictObj.Count; i++) { Console.WriteLine("Key: {0} Value: {1}", _dictObj.Keys.ElementAt(i), _dictObj[_dictObj.Keys.ElementAt(i)]); }
Contains method will check if KeyValuePair is found in collection, returns true or false
_dictObj.Contains(new KeyValuePair<int, string>(1, "C# Dictionary Example"));
You should also look at others C# Data Structures Fundamental.