Зміст курсу
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
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
2. Adding Data
We can use the Add
method to add items to the dictionary:
index
3. Accessing Data
We can access the data in dictionaries using the keys:
index
Following is an example which demonstrates all three:
index
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
Все було зрозуміло?