Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

CSharp Dictionary



How to C# Dictionary

A Dictionary class is a data structure that represents a collection of keys and values pair of data. The key is identical in a key-value pair, and it can have at most one value in the Dictionary, but a value can be associated with many different keys.

This class is defined in the System.Collections.Generic namespace, so you should import or using System.Collections.Generic namespace.

using System.Collections.Generic

Parameters :

TKey - The type of the keys in the dictionary.
TValue - The type of the values in the dictionary.

e.g.

Dictionary<string, string>
Dictionary<string, int>

C# Dictionary examples

Adding Values to Dictionary

Add method in Dictionary takes two parameters, one for the key and one for the value.

Syntax

public void Add(TKey key,TValue value)

example

dictionary.Add("dozen",12);

Key in a Dictionary should not be null, but a value can be if TValue is a reference type. The following dictionary example creates an empty Dictionary < TKey, TValue > of strings with string keys and uses the Add method to add some elements.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
dict.Add(3, "three");
dict.Add(4, "four");

foreach in Dictionary

Retrieve Key-Value pair from Dictionary using foreach loop.

foreach (KeyValuePair<int, string> pair in dict)
{
    MessageBox.Show(pair.Key.ToString() + "  -  " + pair.Value.ToString());
}

Dictionary exceptions

When you add an item to the Dictionary if ItemItem already exists in the Dictionary an exception will be thrown.

 try
{
    dict.Add("two", 2);
}
catch (ArgumentException)
{
    MessageBox.Show("Key already exist ");
}

However, if the specified key already exists in the Dictionary, setting the Item[TKey] property overwrites the old value. In contrast, the Add method throws an exception if a value with the specified key already exists.

Indexer or Dictionary[Key]

When you add ItemItem using indexer, if the key doesn’t exist in the Dictionary, a new item will be added. If the key exists, then the value will be updated with the new value.

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("First", "First Value");
dict["Second"] = "Second value"; //Adds a new element in dictionary
MessageBox.Show(dict["Second"]);
dict["Second"] = "Updated second value"; // Modify the value of existing element to new value
MessageBox.Show(dict["Second"]);

output

Second value
Updated second value

Search for a Key

We can search a Key in Dictionary by using the ContainsKey method to test whether a key exists or not. ContainsKey computes the hashcode for its argument and checks the internal structures in the Dictionary.

if (dict.ContainsKey("four") == true)
{
  MessageBox.Show(dict["four"].ToString ());
}
else
{
  MessageBox.Show("Key does not exist");
}

Dictionary TryGetValue

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. When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the method will return false if it could not found keys instead of throwing an exception.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
dict.Add(3, "three");
dict.Add(4, "four");
string result;
if (dict.TryGetValue(5, out result))
{
    MessageBox.Show(result);
}
else
{
    MessageBox.Show("Unable to find the specified key.");
}

Dictionary: TryGetValue Vs ContainsKey

Dictionary TryGetValue will be faster when compared to ContainsKey. The ContainsKey method uses the same check as TryGetValue, which internally refers to the actual entry location. The Item property actually has nearly identical code functionality as TryGetValue, except that it will throw an exception instead of returning false. When using ContainsKey followed by the ItemItem actually duplicates the lookup functionality, which is the bulk of the computation in this case.

Get dictionary value by key

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
dict.Add(3, "three");
dict.Add(4, "four");
string val = dict[2];
MessageBox.Show(val.ToString());

Note that if the Dictionary doesn’t have a key that equals “2”, that code will throw an exception. If you want to check first, you can use TryGetValue like this:

string dictValue;
if (!dict.TryGetValue(2, out dictValue)) {
   // the key isn't in the dictionary.
   return;
}

Get dictionary key by value

In some situations, you have only dictionary value, and you have to find the key. The following example will help you to find the key using value.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
dict.Add(3, "three");
dict.Add(4, "four");
MessageBox.Show(GetKeyByValue(dict, "three").ToString());
public static int GetKeyByValue(Dictionary<int, string> dict, string val)
{
    int key =0;
    foreach (KeyValuePair<int, string> pair in dict)
    {
        if (pair.Value == val)
        {
            key = pair.Key;
            break;
        }
    }
    return key;
}

How to get the value of Dictionary keys via index?

A dictionary does not use index since it is not its initial purpose. A dictionary uses key-value relation. It does not so because items are not stored continuously in memory. You have one reference which knows where all items are. But none is first or last. If you want to get ItemItem by index, you have to loop through all the elements in Dictionary.

Convert C# dictionary to a JSON String

Serializing data structures containing only numeric or boolean values is fairly straightforward. If you don’t have much to serialize, you can write a method for your specific type. For a Dictionary < int, List < int > > , you can using the following example.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Net;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
private void button1_Click_1(object sender, EventArgs e)
{
  Dictionary<int, List<int>> foo = new Dictionary<int, List<int>>();
  foo.Add(1, new List<int>(new int[] { 1, 2, 3, 4 }));
  foo.Add(2, new List<int>(new int[] { 2, 3, 4, 1 }));
  foo.Add(3, new List<int>(new int[] { 3, 4, 1, 2 }));
  foo.Add(4, new List<int>(new int[] { 4, 1, 2, 3 }));
  DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<int, List<int>>));
  using (MemoryStream ms = new MemoryStream())
  {
      serializer.WriteObject(ms, foo);
      MessageBox.Show(Encoding.Default.GetString(ms.ToArray()));
  }
}

The System.Runtime.Serialization.Json Namespace is in two different DLL’s depending on your .net framework.

  1. In .NET 3.5 It is in System.ServiceModel.Web.dll
  2. In .NET 4.0 and above It is in System.Runtime.Serialization.dll

Dictionary Count Property

C# Dictionary count property returns the number of key/value pairs contained in the Dictionary.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
MessageBox.Show("No of Item in Dictionary : " + dict.Count);

Remove Item from Dictionary

The Remove() method removes an item with the specified key from the dictionary collection.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
dict.Remove(1);
MessageBox.Show("No of Item in Dictionary : " + dict.Count);

Remove All Item from Dictionary

The Dictionary Clear() method removes all items from the collection.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
dict.Clear();
MessageBox.Show("No of Item in Dictionary : " + dict.Count);

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More