SlideShare a Scribd company logo
1 of 27
Download to read offline
PROGRAMMING IN C#
DICTIONARIES AND SETS
ENGR. MICHEAL OGUNDERO
YOU CAN CONTACT ME VIA
PHONE - +2348087365099
SKYPE – MICHEAL OGUNDERO
Email – ogunderoayodeji@gmail.com
CONTENT 2
1
2
3
4
HASH TABLES
DICTIONARIES
SORTED DICTIONARIES
CODES ON GITHUB
HASH TABLE 3
• This is also known as hash map
• It allows mapping keys to particular values
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.
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.
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.
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.
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)
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
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.
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");
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.");
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
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).
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.
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
DICTIONARY EXAMPLE I – PRODUCT LOCATION 17
Dictionary<long, string> products =
new Dictionary<long, string>
{
{ 5900000000000, "A1" },
{ 5901111111111, "B5" },
{ 5902222222222, "C9" }
};
products[5903333333333] = "D7";
try
{
products.Add(5904444444444, "A3");
}
catch (ArgumentException)
{
Console.WriteLine("The entry already
exists.");
}
//print all products
Console.WriteLine("All products:");
if (products.Count == 0)
{
Console.WriteLine("Empty");
}
else
{
foreach (KeyValuePair<long, string>
product in products)
{
Console.WriteLine($" -
{product.Key}: {product.Value}");
}
}
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.");
}
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
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.
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.
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:
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
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;
}
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);
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
Systems Engineering Department,
University of Lagos, Nigeria.
(234) 808-736-5099 Micheal Ogundero
Thank You

More Related Content

What's hot

What's hot (20)

Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
Stack
StackStack
Stack
 
Python programming
Python programmingPython programming
Python programming
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Stacks in Data Structure
Stacks in Data StructureStacks in Data Structure
Stacks in Data Structure
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
The Functional Programming Triad of fold, scan and iterate
The Functional Programming Triad of fold, scan and iterateThe Functional Programming Triad of fold, scan and iterate
The Functional Programming Triad of fold, scan and iterate
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
List interface
List interfaceList interface
List interface
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
1. 3 singly linked list insertion 2
1. 3 singly linked list   insertion 21. 3 singly linked list   insertion 2
1. 3 singly linked list insertion 2
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
Priority Queue
Priority QueuePriority Queue
Priority Queue
 
List
ListList
List
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
 

Similar to Dictionary and sets-converted

Amusing C#
Amusing C#Amusing C#
Amusing C#PVS-Studio
 
CSharp for Unity - Day 1
CSharp for Unity - Day 1CSharp for Unity - Day 1
CSharp for Unity - Day 1Duong Thanh
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...PVS-Studio
 
Vizwik Coding Manual
Vizwik Coding ManualVizwik Coding Manual
Vizwik Coding ManualVizwik
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++Khushal Mehta
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29Bilal Ahmed
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Dictionary e book
Dictionary e bookDictionary e book
Dictionary e booksharmilakt
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26Bilal Ahmed
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans Fabrizio Giudici
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to ProgrammingCindy Royal
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath CommunityRohit Radhakrishnan
 
(2) collections algorithms
(2) collections algorithms(2) collections algorithms
(2) collections algorithmsNico Ludwig
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxRohit Radhakrishnan
 

Similar to Dictionary and sets-converted (20)

Amusing C#
Amusing C#Amusing C#
Amusing C#
 
CSharp for Unity - Day 1
CSharp for Unity - Day 1CSharp for Unity - Day 1
CSharp for Unity - Day 1
 
PHP Reviewer
PHP ReviewerPHP Reviewer
PHP Reviewer
 
Chapter 3 part2
Chapter 3  part2Chapter 3  part2
Chapter 3 part2
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...
 
Vizwik Coding Manual
Vizwik Coding ManualVizwik Coding Manual
Vizwik Coding Manual
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Dictionary e book
Dictionary e bookDictionary e book
Dictionary e book
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community
 
Collection
CollectionCollection
Collection
 
(2) collections algorithms
(2) collections algorithms(2) collections algorithms
(2) collections algorithms
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
 

More from Micheal Ogundero

csharp repitition structures
csharp repitition structurescsharp repitition structures
csharp repitition structuresMicheal Ogundero
 
selection structures
selection structuresselection structures
selection structuresMicheal Ogundero
 
escape sequences and substitution markers
escape sequences and substitution markersescape sequences and substitution markers
escape sequences and substitution markersMicheal Ogundero
 
A simple program C# program
A simple program C# programA simple program C# program
A simple program C# programMicheal Ogundero
 
datatypes_variables_constants
datatypes_variables_constantsdatatypes_variables_constants
datatypes_variables_constantsMicheal Ogundero
 
2 robot types_classifications
2 robot types_classifications2 robot types_classifications
2 robot types_classificationsMicheal Ogundero
 
c# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventionsc# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming ConventionsMicheal Ogundero
 
csharp_Passing_parameters_by_value_and_reference
csharp_Passing_parameters_by_value_and_referencecsharp_Passing_parameters_by_value_and_reference
csharp_Passing_parameters_by_value_and_referenceMicheal Ogundero
 
C# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesC# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesMicheal Ogundero
 

More from Micheal Ogundero (13)

static methods
static methodsstatic methods
static methods
 
csharp repitition structures
csharp repitition structurescsharp repitition structures
csharp repitition structures
 
selection structures
selection structuresselection structures
selection structures
 
escape sequences and substitution markers
escape sequences and substitution markersescape sequences and substitution markers
escape sequences and substitution markers
 
A simple program C# program
A simple program C# programA simple program C# program
A simple program C# program
 
c# operators
c# operatorsc# operators
c# operators
 
datatypes_variables_constants
datatypes_variables_constantsdatatypes_variables_constants
datatypes_variables_constants
 
2 robot types_classifications
2 robot types_classifications2 robot types_classifications
2 robot types_classifications
 
History of robots
History of robotsHistory of robots
History of robots
 
c# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventionsc# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventions
 
c# Enumerations
c# Enumerationsc# Enumerations
c# Enumerations
 
csharp_Passing_parameters_by_value_and_reference
csharp_Passing_parameters_by_value_and_referencecsharp_Passing_parameters_by_value_and_reference
csharp_Passing_parameters_by_value_and_reference
 
C# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesC# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data Types
 

Recently uploaded

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)Dr. Mazin Mohamed alkathiri
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 

Recently uploaded (20)

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 

Dictionary and sets-converted

  • 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
  • 17. DICTIONARY EXAMPLE I – PRODUCT LOCATION 17 Dictionary<long, string> products = new Dictionary<long, string> { { 5900000000000, "A1" }, { 5901111111111, "B5" }, { 5902222222222, "C9" } }; products[5903333333333] = "D7"; try { products.Add(5904444444444, "A3"); } catch (ArgumentException) { Console.WriteLine("The entry already exists."); } //print all products Console.WriteLine("All products:"); if (products.Count == 0) { Console.WriteLine("Empty"); } else { foreach (KeyValuePair<long, string> product in products) { Console.WriteLine($" - {product.Key}: {product.Value}"); } }
  • 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
  • 27. Systems Engineering Department, University of Lagos, Nigeria. (234) 808-736-5099 Micheal Ogundero Thank You