Dictionary:
Dictionary in C# Programming is same like English Dictionary. English Dictionary is a collection of words and their definitions, often listed Alphabetically in one or more specific Languages. In the Same way, The C# Dictionary is a Collection of Keys and Values, where Key is like a Word and Value is Like Definition.
Dictionary Declaration:
Dictionary is a Generic Collection Included in the System.Collection.Generics Namespace. We can Declare a Dictionary using the Following Syntax:
Dictionary<TKey, TValue> DictionaryName = New Dictionary<TKey, TValue>();
Dictionary Class provide some Useful properties and Methods to work with Dictionary in C# Language. some of the useful and most common properties of Dictionary<TKey, TValue> class are:
Properties | Description |
---|---|
Count | Gets the number of key/value pairs contained in the Dictionary. |
IsReadOnly | Returns a Boolean indicating whether the Dictionary is read-only. |
item[TKey] | Gets or sets the value associated with the specified key. |
Keys | Gets a collection containing the keys in the Dictionary. |
Values | Gets a collection containing the values in the Dictionary. |
Following are the most commonly used methods of Dictionary<TKey, TValue> Class:
Methods | Description |
---|---|
Add(TKey, TValue) | Adds the specified key and value to the dictionary. |
Clear() | Removes all keys and values from the Dictionary. |
ContainsValue() | Determines whether the Dictionary contains the specified key. |
ContainsKey() | Determines whether the Dictionary contains the specified key. |
Finalize() | Allows an object to try to free resources and perform other clean-up operations before it is reclaimed by garbage collection. |
GetType() | Gets the Type of the current instance. |
Remove(TKey) | Removes the value with the specified key from the Dictionary. |
Remove(T item) | Removes the first occurrence of specified item from the Dictionary. |
ToString() | Returns a string that represents the current object. |
TryGetValue(TKey, TValue) | Gets the value associated with the specified key. |
For complete list of properties and methods, please visit Microsoft's C# documentation. |
Let's have a simple example to know, how we can add values in dictionary, how to remove or update values. and to work with keys. we will use different methods to work with dictionary collection.
/*Example - Dictionary<TKey, TValue> - InfoBrother*/
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new dictionary of strings, with string keys.
Dictionary<string, string> openWith =
new Dictionary<string, string>();
/* Add some elements to the dictionary. We can't add
duplicate keys, but our values can be duplicates. */
openWith.Add("C#", "VisualStudio");
openWith.Add("C++", "BorlandTurbo");
openWith.Add("Java", "NetBeans");
openWith.Add("Python", "PyCharm");
/* The Add method throws an exception if the new key is
already in the dictionary. */
try
{ //Add New item in the dictionary
openWith.Add("C#", "NetBeans");
}
catch (ArgumentException)
{ //if Key already exist. throw this exception.
Console.WriteLine("An element with Key = \"C#\" already exists.");
}
/* The Item property is another name for the indexer, so we
can omit its name when accessing elements. */
Console.WriteLine("For key = \"C++\", value = {0}.",
openWith["C++"]);
/* The indexer can be used to change the value associated
with a key. */
openWith["C++"] = "VisualStudio";
Console.WriteLine("For key = \"C++\", value = {0}.",
openWith["C++"]);
/* If a key does not exist, setting the indexer for that key
adds a new key/value pair. */
openWith["Code"] = "VisualStudio";
/* The indexer throws an exception if the requested key is
not in the dictionary. */
try
{
Console.WriteLine("For key = \"CSS\", value = {0}.",
openWith["CSS"]);
}
catch (KeyNotFoundException)
{
Console.WriteLine("Key = \"CSS\" is not found.");
}
/* When a program often has to try keys that turn out not to
be in the dictionary, TryGetValue can be a more efficient
way to retrieve values. */
string value = "";
if (openWith.TryGetValue("CSS", out value))
{
Console.WriteLine("For key = \"CSS\", value = {0}.", value);
}
else
{
Console.WriteLine("Key = \"CSS\" is not found.");
}
/*ContainsKey can be used to test keys before inserting them.*/
if (!openWith.ContainsKey("Js"))
{
openWith.Add("JS", "Eclipse");
Console.WriteLine("Value added for key = \"JS\": {0}",
openWith["JS"]);
}
/* When we use foreach to enumerate dictionary elements,
the elements are retrieved as KeyValuePair objects.*/
Console.WriteLine();
foreach (KeyValuePair<string, string> kvp in openWith)
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
openWith.Values;
/* The elements of the ValueCollection are strongly typed
with the type that was specified for dictionary values.*/
Console.WriteLine();
foreach (string s in valueColl)
{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys;
/* The elements of the KeyCollection are strongly typed
with the type that was specified for dictionary keys. */
Console.WriteLine();
foreach (string s in keyColl)
{
Console.WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"C#\")");
openWith.Remove("C#");
if (!openWith.ContainsKey("C#"))
{
Console.WriteLine("Key \"C#\" is not found.");
}
Console.ReadKey();
}
}
Dictionary<TKey, TValue> Class:
For key = "C++", value = BorlandTurbo. For key = "C++", value = VisualStudio. Key = "CSS" is not found. Key = "CSS" is not found. Value added for key = "JS": Eclipse Key = C#, Value = VisualStudio Key = C++, Value = VisualStudio Key = Java, Value = NetBeans Key = Python, Value = PyCharm Key = Code, Value = VisualStudio Key = JS, Value = Eclipse Value = VisualStudio Value = VisualStudio Value = NetBeans Value = PyCharm Value = VisualStudio Value = Eclipse Key = C# Key = C++ Key = Java Key = Python Key = Code Key = JS Remove("C#") Key "C#" is not found.