DEV Community

Cover image for Dictionary C#. Easier than we think.
Abdullah al Mubin
Abdullah al Mubin

Posted on

Dictionary C#. Easier than we think.

What is Dictionary:

The Dictionary is a generic collection of key-value pair of data. It contains a unique key, we can easily get our specific data using that unique key. The dictionary is the most useful and popular data structure whenever we need to find value based on key..

Syntax:

Dictionary<TKey, TValue> dictionaryObj = new Dictionary<TKey, TValue>();

in the above line, dictionaryObj is name of the dictionary, Tkey is The type of key we pass in the dictionaryObj and TValue is The type of value we pass in the dictionaryObj.

TKey and TValue can be any data type.

Characteristics

  • Comes under System.Collections.Generic namespace.
  • Dictionary stores key-value pairs.
  • Implements IDictionary interface.
  • Keys must be unique and cannot be null.
  • Values can be null or duplicate.
  • Values can be accessed by passing associated key in the indexer e.g. myDictionary[key]
  • Elements are stored as KeyValuePair objects.
  • It is faster than a Hashtable because there is no boxing and unboxing.

Create a Dictionary

We have already seen the syntax, let's try to create a dictionary,

Dictionary<int, string> myDictionary = new Dictionary<int, string>();
Enter fullscreen mode Exit fullscreen mode

In the above code, key will be int and value will be string.

let's add some value on it, here, 1 is key and value is myName

myDictionary.Add(1, "myName");
Enter fullscreen mode Exit fullscreen mode

put below code in our compiler and run the code.

Dictionary<int, string> myDictionary = new Dictionary<int, string>();
myDictionary.Add(1, "mubin");

foreach (var item in myDictionary)
{
Console.WriteLine(item.Key + ": and value is: " + item.Value);
}
Enter fullscreen mode Exit fullscreen mode

Then the output will be,
1: and value is: mubin

Image description

let's put an object in a dictionary,

Declare a class UserDetails

class UserDetails
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    }
Enter fullscreen mode Exit fullscreen mode

Now declare a dictionary using that class

Dictionary<int, UserDetails> userDetails = new Dictionary<int, UserDetails>();
userDetails.Add(1, new UserDetails { Name = "Galib", Age = 123, Address = "Naogaon" });

foreach (var item in userDetails)
{
Console.WriteLine("Key is: "+item.Key + " Name " + item.Value.Name + " Age: " + item.Value.Age + " Address: " + item.Value.Address);
}

Enter fullscreen mode Exit fullscreen mode

if we run above code then the result will be

Image description

Get Data from Dictionary:

To get data from dictionary we can use the square bracket notation to access an item data in the dictionary.

Dictionary<int, string> myDictionary = new Dictionary<int, string>();
myDictionary.Add(1, "mubin");

string userName = myDictionary[1]; 
// Here 1 is a key, using 1 we can get value
Enter fullscreen mode Exit fullscreen mode

Update Data in a Dictionary

To update data, We can use square bracket and notation then assign new value.

Dictionary<int, string> myDictionary = new Dictionary<int, string>();
myDictionary.Add(1, "mubin");
myDictionary[1] = "Update Username";
Enter fullscreen mode Exit fullscreen mode

Delete Data in a Dictionary

We can use remove method to delete data in a dictionary.

myDictionary.Remove(1);
Enter fullscreen mode Exit fullscreen mode

Properties of Dictionary:

Count
Count used to get the total length/number of key-value pairs in the Dictionary.

int count = myDictionary.Count;
Enter fullscreen mode Exit fullscreen mode

Values
Values used to get a collection of all the values in the Dictionary.

var values = myDictionary.Values;
Enter fullscreen mode Exit fullscreen mode

Keys
Get a collection of all the keys in the Dictionary.

var keys = myDictionary.Keys;
Enter fullscreen mode Exit fullscreen mode

C# Dictionary Methods

Add()
Add(TKey key, TValue value): Add a new key-value pair item to the Dictionary.

Dictionary<string, int> bookPrice = new Dictionary<string, int>();
bookPrice.Add("Physics", 2.20);
bookPrice.Add("Chemistry", 1.80);
Enter fullscreen mode Exit fullscreen mode

ContainsKey()
ContainsKey(TKey key): Returns a boolean indicating whether the Dictionary contains the specified key.

bool containsPhysics = bookPrice.ContainsKey("Physics"); // returns  true;
bool containsHistory = bookPrice.ContainsKey("History"); // returns false;
Enter fullscreen mode Exit fullscreen mode

Note: If the key is null, an ArgumentNullException will be thrown, and if the requested key is not in the dictionary, a KeyNotFoundException will be thrown.

ContainsValue()
Returns a boolean indicating whether the Dictionary contains the specified value.

bool value = bookPrice.ContainsValue(1.80); // returns true;
Enter fullscreen mode Exit fullscreen mode

Remove()
Remove() method deletes the value with the specified key from the Dictionary.
If the key is found and the item is successfully removed, it returns true; otherwise false.

// Use the Remove method to remove a key / value pair.
Console.WriteLine("\nRemove(\"107\")\n");
bookPrice.Remove("Physics");

// Check if item is removed from the dictionary object.
if (!bookPrice.ContainsKey("Physics"))
{
  Console.WriteLine("Key \"107\" is not found.");
}
Enter fullscreen mode Exit fullscreen mode

TryGetValue()
This method is used to get the value for a specific key, which allows you to handle the case where the key does not exist. It will not throw an error if the key doesn’t exist in the collection.

int physicsPrice;
if (bookPrice.TryGetValue("Physics", out physicsPrice))
{
    Console.WriteLine($"The price of a Physics book is {physicsPrice}.");
}
else
{
    Console.WriteLine("The Physics book is not available.");
}
Enter fullscreen mode Exit fullscreen mode

Clear()
Removes all key-value pairs from the Dictionary.

bookPrice.Clear();
Enter fullscreen mode Exit fullscreen mode

That's all for today.. seee ya.

Top comments (0)