The document discusses dictionaries and sets in C#, including hash tables, sorted dictionaries, and examples. It begins with an introduction to hash tables and how they allow fast lookup of values based on keys. Generic and non-generic dictionaries are described, along with properties like Count and methods like Add. Examples include a phonebook using a hashtable and product locations using a dictionary. Sorted dictionaries are also covered, providing sorted key access but with slower performance. Code examples demonstrate an encyclopedia application using a sorted dictionary.
1. PROGRAMMING IN C#
DICTIONARIES AND SETS
ENGR. MICHEAL OGUNDERO
YOU CAN CONTACT ME VIA
PHONE - +2348087365099
SKYPE – MICHEAL OGUNDERO
Email – ogunderoayodeji@gmail.com
3. HASH TABLE 3
• This is also known as hash map
• It allows mapping keys to particular values
4. HASH TABLE …. 4
• It is assumed that it has a very fast lookup for a value based on the
key which should be the O(1) operation.
• The Hash function takes the Key to generate an index of a bucket,
where the Value can be found.
• It is usually used in many real-world applications, such as for
associative arrays, database indices, or cache systems.
5. THE HASH FUNCTION 5
• The hash function is critical and ideally it should generate a unique
result for all keys.
• However, it is possible that the same result is generated for
different keys. Such a situation is called a hash collision and can be
addressed.
6. HASH TABLE TYPES 6
• There are two variants of the hash table-related classes, namely:
1. non-generic (Hashtable) and
2. generic (Dictionary).
We start by learning the non-generic hash table.
7. HASH TABLE (GENERIC TYPE) - GET AND SET
VALUES
7
As the Hashtable class is a non-generic variant of hash table-related classes, you
need to cast the returned result to the proper type (for example, string), as shown
below:
string value = (string)hashtable["key"];
You can set the value like this:
hashtable["key"] = "value";
N.B: the null value is incorrect for a key of an element, but it is acceptable
for value of an element.
8. HASH TABLE - PROPERTIES 8
The class is equipped with a few properties, which makes it possible to
• get the number of stored elements (Count)
• add a new element (Add),
• remove an element (Remove),
• to remove all elements (Clear)
• check whether the collection contains a particular key
(Contains and ContainsKey) or a given value (ContainsValue).
• return the collection of keys or values (keys and values respectively)
9. HASH TABLE – GET ALL ENTRIES 9
foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine($"{entry.Key} - {entry.Value}");
}
N.B: The datatype for each set of pairs is a DictionaryEntry Object
10. HASH TABLE EXAMPLE - PHONEBOOK 10
As an example, you will create an application for a phone book. The Hashtable class
will be used to store entries where the person name is a key and the phone number
is a value, as shown below:
The program will demonstrate how to add elements to the collection, check the
number of stored items, iterate through all of them, check whether an element with
a given key exists, as well as how to get a value based on the key.
11. HASH TABLE EXAMPLE - PHONEBOOK 11
//Create a new instance of hashtable
Hashtable phoneBook = new Hashtable()
{
{ "Damilola Afolabi", "08127609067" },
{ "David Ogunleye", "08121200853" },
{ "Inyang Naomi", "08135171248" }
};
phoneBook["Ayomide Fagoroye"] = "08111851538"; // using indexer
phoneBook["Ene Ebube"] = "08159962308";
try
{
phoneBook.Add("Bolu Omotoro", "08077329962");
phoneBook.Add("Nmesoma Ngozi", "09032200986");
}
catch (ArgumentException)
{
Console.WriteLine("The entry already exists.");
}
//remove a contact
phoneBook.Remove("Ayomide Fagoroye");
12. HASH TABLE EXAMPLE - PHONEBOOK 12
//print out all phonenumbers
Console.WriteLine("Phone numbers:");
if (phoneBook.Count == 0)
{
Console.WriteLine("Empty");
}
else
{
foreach (DictionaryEntry entry in phoneBook)
{
Console.WriteLine(" - {0}: {1}”,entry.Key,entry.Value);
}
}
// search phonebook by name
Console.WriteLine();
Console.Write("Search by name: ");
string nameOrNumber = Console.ReadLine();
if (phoneBook.Contains(nameOrNumber)) //extend this line to also search by value
{
string number = (string)phoneBook[nameOrNumber];
Console.WriteLine("Found phone number: {0}”, number);
}
else
{
Console.WriteLine("The entry does not exist.");
13. DICTIONARIES 13
• So far, we have learnt that the Hashtable class is a non-generic variant
of the hash table-related classes.
• Dictionary is the strongly typed version of the hash table-related
classes.
• Therefore casting to the string type is unnecessary.
• First of all, you should specify two types namely, a type of a key and a
value, while creating an instance of the Dictionary class.
Dictionary<string, string> myDictionary = new Dictionary<string, string>
{ { "Key 1", "Value 1" }, { "Key 2", "Value 2" } };
myDictionary["key"] = "value"; // using the indexer
14. DICTIONARIES - PROPERTIES 14
• Similar to the non-generic variant, the key cannot be equal to null, but a value can
be, of course, if it is allowed by data-type.
• The performance of getting a value of an element, adding a new element, or
updating an existing one, is approaching the O(1) operation.
The Dictionary class is equipped with a few properties, which makes it possible to
• get the number of stored elements (Count),
• return the collection of keys or values (Keys and Values, respectively).
• adda new element (Add),
• remove an item (Remove), removing all elements (Clear),
• check whether the collection contains a particular key (ContainsKey) or a given
value (ContainsValue).
• You can also use the TryGetValue method to try to get a value for a given key and
return it (if the element exists) or return null (otherwise).
15. DICTIONARIES – GETTING ALL ENTRIES 15
foreach (KeyValuePair<string, string> pair in dictionary)
{
Console.WriteLine($"{pair.Key} - {pair.Value}");
}
N.B: the process of checking whether the collection contains a given value is the O(n)
operation and requires you to search the entire collection for the particular value.
16. DICTIONARY EXAMPLE I – PRODUCT LOCATION 16
• The application helps employees of a shop to find the location of where a product
should be placed.
• Let's imagine that each employee has a phone with your application, which is
used to scan the code of the product and the application tells them that the
product should be located in area B2 or A4.
• As the number of products in the shop is often very high, it is necessary to find
results quickly. For this reason, the data of products together with their locations
will be stored in the hash table, using the generic Dictionary class.
• The key will be the barcode, while the value will be the area code, as shown
below
18. DICTIONARY EXAMPLE I – PRODUCT LOCATION 18
Console.WriteLine();
Console.Write("Search by barcode: ");
long barcode =
long.Parse(Console.ReadLine());
if (products.TryGetValue(barcode, out
string location))
{
Console.WriteLine($"The product is in
the area {location}.");
}
else
{
Console.WriteLine("The product does
not exist.");
}
19. DICTIONARY EXAMPLE II – USER DETAILS 19
This example will show you how to store more complex data in the dictionary. In this
scenario, you will create an application that shows details of a user based on his or
her identifier, as shown in the following diagram:
The code can be found on GitHub for practice
https://github.com/EngrMikolo/Hashtables
20. SORTED DICTIONARIES 20
• Both non-generic and generic variants of the hash table-related classes do not
keep the order of the elements.
• you can use another data structure, the sorted dictionary, to solve this problem
and keep keys sorted all the time. Therefore, you can easily get the sorted
collection whenever necessary.
• The sorted dictionary is implemented as the SortedDictionary generic class,
available in the System.Collections.Generic namespace.
• You can specify types for keys and values while creating a new instance of
the SortedDictionary class.
21. SORTED DICTIONARIES - PROPERTIES 21
• The class contains similar properties and methods to Dictionary which are already
familiar with from the previous hashtables.
• the SortedDictionary class has some performance drawbacks in comparison
with Dictionary, because retrieval, insertion, and removal are
the O(logn) operations, where n is the number of elements in the collection,
instead of O(1).
N.B: choosing a proper data structure is not an easy task and you should think
carefully about the scenarios in which particular data structures will be used and
take into account the both pros and cons.
22. SORTED DICTIONARIES EXAMPLE -
ENCYCLOPEDIA
22
You will create a simple encyclopedia, where you can add entries, as well as show its
full content.
The encyclopedia can contain millions of entries, so it is crucial to provide its users
with the possibility of browsing entries in the correct order, alphabetically by keys, as
well as finding entries quickly. For this reason, the sorted dictionary is a good choice
in this example.
The idea of the encyclopedia is shown in the following diagram:
23. SORTED DICTIONARIES – ENCYCLOPEDIA
APPLICATION USERS’ SPECIFICATIONS
23
When the program is launched:
• it presents a simple menu with two options, namely [a] - add and [l] - list.
• After pressing the A key, the application asks you to enter the name and
explanation for the entry.
• If the provided data are correct, a new entry is added to the encyclopedia.
• If the user presses the L key, the data of all entries, sorted by keys, are presented
in the console.
• When any other key is pressed, the additional confirmation is shown and,
• if confirmed, the program exits.
Assignment: Design a flow chart for the encyclopedia application using Microsoft
visio app.
* To be submitted before the next 24 hours
24. SORTED DICTIONARIES EXAMPLE - CODE 24
SortedDictionary<string, string> encyclopedia =
new SortedDictionary<string, string>();
do
{
Console.Write("Choose an option ([a] - add, [l] - list): ");
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine();
if (keyInfo.Key == ConsoleKey.A)
{
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Enter the name: ");
string word = Console.ReadLine();
Console.Write("Enter the explanation: ");
string explanation = Console.ReadLine();
encyclopedia[word] = explanation;
Console.ForegroundColor = ConsoleColor.Gray;
}
25. SORTED DICTIONARIES EXAMPLE - CODE 25
else if (keyInfo.Key == ConsoleKey.L)
{
Console.ForegroundColor = ConsoleColor.Green;
foreach (KeyValuePair<string, string> definition
in encyclopedia)
{
Console.WriteLine($"{definition.Key}: { definition.Value}");
}
Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Do you want to exit the program? Press[y](yes) or[n](no).");
Console.ForegroundColor = ConsoleColor.Gray;
if (Console.ReadKey().Key == ConsoleKey.Y)
{
break;
}
}
}
while (true);
26. CODES 26
Kindly visit my github page for the code
https://github.com/EngrMikolo/Hashtables
• You can also fork the repo to extend the code