Conteúdo do Curso
C# Beyond Basics
C# Beyond Basics
What are Dictionaries?
In Arrays, we access data through indexing (arrayName[index]
). In an Array, every value (element) has a unique index, which is used for accessing that value, therefore we can say that an Array has an index-value structure.
There's a similar structure called a Dictionary, in which we have key-value pairs instead. While an index is always an integer number, a key can be of any basic data type, however it's commonly a string
.
The following illustration shows an example illustration of dictionary which stores the number of different fruits:
1. Creating a Dictionary
We can declare a dictionary using the following syntax:
index
IDictionary<keyDataType, valueDataType> dictionaryName = new Dictionary<keyDataType, valueDataType>();
Here keyDataType
represents the data type of the key while the valueDataType
represents the data type of the values. dictionaryName
is the name of the dictionary.
An implicit declaration is also valid:
index
var dictionaryName = new Dictionary<keyDataType, valueDataType>();
2. Adding Data
We can use the Add
method to add items to the dictionary:
index
dictionaryName.Add(keyName, value);
3. Accessing Data
We can access the data in dictionaries using the keys:
index
dictionaryName[keyName]
Following is an example which demonstrates all three:
index
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { var student = new Dictionary<string, string>(); student.Add("name", "Noah"); student.Add("country", "Netherlands"); student.Add("subject", "Computer Science"); Console.WriteLine(student["name"]); Console.WriteLine(student["country"]); Console.WriteLine(student["subject"]); } } }
In Dictionaries, Count
attribute shows the number of key-value pairs stored in it. Remove
method takes in a key and removes that key-value pair from the dictionary. Clear
method simply removes all key-value pairs from a dictionary. It will be a good code reading exercise to read and understand the usage of Count
, Remove
and Clear
from the following code:
index
using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { var numbers = new Dictionary<int, string>(); numbers.Add(0, "Zero"); numbers.Add(1, "One"); numbers.Add(2, "Two"); numbers.Add(3, "Three"); numbers.Add(4, "Four"); numbers.Add(5, "Five"); Console.WriteLine(numbers.Count); // Output: 6 numbers.Remove(3); Console.WriteLine(numbers.Count); // Output: 5 numbers.Clear(); Console.WriteLine(numbers.Count); // Output: 0 } } }
Obrigado pelo seu feedback!