In this article we will talk about Dictionary which is a collection class
Dynamic Size
Standard arrays have a fixed size; In the programming phase, the size of the array is specified and the program’s target has been changed. The dictionary is variable in size. The dimension is dynamically changing according to the process of adding and removing elements.
Basic Structure of the Dictionary Class
The standard elements are placed in the memory in order to insert the elements. When starting from scratch, an element was given an index value and we were given access to the elements through those indexes. ArrayList, one of the collection classes, has the same situation. The Directory is organized ArrayList so we can access an element by index number.
In the collection of dictionary, there are two concepts, Key and Value. Make the subject clearer; When you add them to standard arrays, you can think of value as the key we use for those according to those elements.
Each Value must have a different Key, so the Keys in your collection will be different.
Now, let’s continue to review the Dictionary Class after preparing a simple C # console application on the start menu.
C# Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Program { static void Main(string[] args) { Dictionary<int, string> students = new Dictionary<int, string>(); students.Add(25, "Mell Wells"); students.Add(65, "Jaime Pickett"); students.Add(14, "Cameron Tran"); students.Add(42, "Marley Lawson"); students.Add(43, "Riley Willis"); students.Add(12, "Logan Baker"); Console.ReadLine(); } } |
Output:
Let’s explain our short sample;
We have prepared an application where the tudents’ number is entered and the student’s name-surname is printed on the screen.
We kept the key of the student as Key, and the name-surname information as Value. We have specified the data type of this type of key as int, and the data type of the value as string.
Directory Methods and Properties
ContainsKey() Method
It will return FALSE if the given value is not contains, if it contains it returns TRUE.
1 2 3 | bool result = students.ContainsKey(14); |
Clear() Method
Erases all Key-Value pairs in the collection.
1 2 3 | students.Clear(); |
Count Property
It returns count of the key-values in the collection.
1 2 3 | int itemCount = students.Count; |
Remove(TKey key) Method
if the element is successfully found and removed; otherwise, false
. This method returns false
if key
is not found in the Dictionary
1 2 3 | bool removed = students.Remove(14); |
Add(TKey key, TValue value) Method
Adds the specified key and value to the dictionary.
1 2 3 | students.Add(25, "Tyler Walker"); |
List Items
list items of directory using foreach statement
1 2 3 4 5 6 | foreach (KeyValuePair<int, string> item in students) { Console.WriteLine("Number:{0} - Name:{1}", item.Key, item.Value); } |