Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Dictionary in C# Tutorial

C# Dictionary, IDictionary Object

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
Method Description
Add Add key-value pairs <TKey, TValue> in Dictionary collection.
Add Adds an item with a key and value into the Dictionary.
TryGetValue Returns true and specified key assigns value in (out) parameter, if key does not exists then return false.
ContainsKey Checks whether the specified key (integer) exists in Dictionary object collection
Contains Checks whether the specified KeyValuePair exists in Dictionary<TKey, TValue>.


C# Dictionary Example

Note: While adding in Dictionary object, you cannot add duplicate or null keys in C# Dictionary, 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");

Retrieve value from C# Dictionary object Example

Two ways you can retrieve value from Dictionary object.

  • To retrieve single value from C# Dictionary object using key
    Console.WriteLine(_dictObj[1]);
    If the specified key does not exist then it will throw KeyNotFoundException.

  • To retrieve all values from Dictionary object using keys-collection
    for (int i = 0; i < _dictObj.Count; i++)
    {
    Console.WriteLine("Key: {0} Value: {1}", _dictObj.Keys.ElementAt(i), _dictObj[_dictObj.Keys.ElementAt(i)]);
    }

TryGetValue Example in C# Dictionary
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.");
}


Contains Example in C# Dictionary
Contains method will check if KeyValuePair is found in collection, returns true or false
_dictObj.Contains(new KeyValuePair<int, string>(1, "C# Dictionary Example"));

 
Dictionary in C#
in C# Tutorials
Learn C# Online Tutorial


Group Training