Dictionary C#. Easier than we think.
Tags: csharp, oop, webdev, dotnet
Published: 2023-08-05 14:25:49

## What is Dictionary:
**The Dictionary<TKey, TValue>** 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<TKey, TValue> stores key-value pairs.
- Implements IDictionary<TKey, TValue> 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<TKey, TValue> 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>();
```

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");
```

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);
}
```
Then the output will be,
`1: and value is: mubin`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yiyavb2vp6lupphtnk5h.png)


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; }
    }
```

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);
}

```
if we run above code then the result will be 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0cky4vl0t9azbm710k1o.png)

## 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
```

## 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";
```

## Delete Data in a Dictionary
We can use remove method to delete data in a dictionary.

```
myDictionary.Remove(1);
```

## Properties of Dictionary:

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

```
int count = myDictionary.Count;
```

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

```
var values = myDictionary.Values;
```

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

```
var keys = myDictionary.Keys;
```


## 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);
```

**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;
```

> 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;
```

**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.");
}
```

**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.");
}
```

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

```
bookPrice.Clear();
```

That's all for today.. seee ya.