Key=Value
Most hash tables are made of string keys and string values
but the key or the value can also be a number or a more complex item. There is
no strict rule as to what you use a hash table for. When you create one, it is
up to you to decide what you want to do with it.
Practical
Learning: Introducing Hash Tables |
|
- Create a new Console Application named GeorgetownCleaningServices7
-
To save the project, on the Standard toolbar, click the Save All
button
- Accept all the defaults and click Save
- To cre ate a new class, on the main menu, click Project -> Add Class...
- Set the Name to CleaningOrderDetails and click Add
- Change the file as follows:
using System;
namespace GeorgetownCleaning7
{
[Serializable]
public class CleaningOrderDetails
{
// Receipt identification
public int ReceiptNumber;
public string CustomerName;
public string CustomerPhoneNumber;
// The date the cleaning items were deposited
public DateTime OrderDate;
public DateTime OrderTime;
// Numbers to represent cleaning items
public uint NumberOfShirts;
public uint NumberOfPants;
public uint NumberOtherItems;
// Price of items
public decimal PriceOneShirt = 0.95M;
public decimal PriceAPairOfPants = 2.95M;
public decimal PriceOtherItems = 4.55M;
public decimal TaxRate = 0.0575M; // 5.75%
// Each of these sub totals will be used for cleaning items
public decimal SubTotalShirts;
public decimal SubTotalPants;
public decimal SubTotalOtherItems;
// Values used to process an order
public decimal TotalOrder;
public decimal TaxAmount;
public decimal SalesTotal;
}
}
|
- Save the file
The .NET Framework supports hash tables at different levels
but probably the most common class used is called Hashtable. The Hashtable
class implements the ISerializable interface that makes it possible for
the list to be serialized, the ICollection interface used to keep track
of the number of items in the list, the IEnumerable interface that would
allow you to use the foreach loop.
Before using a hash table, you can declare a variable of
type Hashtable using one of its constructors such as the default one.
Here is an example:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
return 0;
}
}
}
In
this case, the primary list would be empty.
To add an item to the table, you can call the Add()
method. Its syntax is:
public virtual void Add(object Key, object Value);
As you can see, you must provide the key and the value as
the first and second arguments to the method. Here are examples of calling the Add()
method:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
return 0;
}
}
}
When calling the Add() method, you must provide a
valid Key argument: it can be null. For example, the following code would
produce an error:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
Chelsea20062007.Add(null, "Essien");
return 0;
}
}
}
This would produce:
Unhandled Exception: System.ArgumentNullException:
Key cannot be null.
When adding the items to the list, each key must be unique:
you cannot have two exact keys. If you try adding a key that exists already in
the list, the computer would throw an ArgumentException exception. Based
on this, the following code would not work because, on the third call, a
"Michael" key exists already:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
Chelsea20062007.Add("Michael", "Essien");
return 0;
}
}
}
This would produce:
Unhandled Exception: System.ArgumentException:
Item has already been added. Key
in dictionary: 'Michael' Key being added: 'Michael'
Besides the Add() method, you can use the indexed
property of the Hashtable class to add an item to the list. To do this,
enter the Key in the square brackets of the property and assign it the
desired Value. Here is an example:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
Chelsea20062007["Claude"] = "Makelele";
return 0;
}
}
}
After adding one or more items to the list, they are stored
in two collections. The keys are stored in a collection represented by a
property named Keys. The values are stored in the Values property.
Each of these properties is of type ICollection.
Accessing the Items of a Hash Table
|
|
Although, or because, the key and value are distinct, to
consider their combination as a single object, the .NET Framework provides the DictionaryEntry
structure. To access an item, you can use the foreach loop to visit each
item. To support the foreach loop, the Hashtable class implements the IEnumerable.GetEnumerator()
method. In this case, the item is of type DictionaryEntry: it contains a Key
and a Value in combination. The DictionaryEntry structure contains
two properties named Key and Value to identify the components of a combination.
Here is an example:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
Chelsea20062007["Claude"] = "Makelele";
foreach (DictionaryEntry entry in Chelsea20062007)
Console.WriteLine("{0} {1}", entry.Key, entry.Value);
Console.WriteLine();
return 0;
}
}
}
This would produce:
Didier Drogba
Michael Ballack
Claude Makelele
Press any key to continue . . .
Practical
Learning: Using a Hash Table |
|
- To cre ate a new class, in the Class View, right-click
GeorgetownCleaningServices7 -> Add -> Class...
- Set the Name to Customers and press Enter
- Change the file as follows:
using System;
namespace GeorgetownCleaningServicesHatch1
{
[Serializable]
public class Customer
{
public string Name;
public string PhoneNumber;
}
}
|
- To create a new class, in the Solution Explorer, right-click
GeorgetownCleaningServices7 -> Add -> Class...
- Set the Name to CleaningOrderManagement and click Add
- Change the file as follows:
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
namespace GeorgetownCleaningServicesHatch1
{
public class CleaningDeposit
{
// We need a global customer info to
// modify/update it from anywhere
string strCustomerName;
string strPhoneNumber;
// This is the list that will hold the cleaning orders
ArrayList CleaningOrders;
// This is a list that will hold the combinations of
// a customer's name and telephone number
private Hashtable Customers;
public CleaningOrderDetails depot;
public CleaningDeposit()
{
this.Customers = new Hashtable();
this.CleaningOrders = new ArrayList();
this.strPhoneNumber = "(000) 000-0000";
this.strCustomerName = "Unknown";
this.depot = new CleaningOrderDetails();
CheckDefaultFolder();
CheckDefaultFiles();
}
private void CheckDefaultFolder()
{
DirectoryInfo diGCS =
new DirectoryInfo(@"C:\Georgetown " +
"Cleaning Services");
try
{
if (!diGCS.Exists)
diGCS.Create();
}
catch (IOException)
{
Console.WriteLine("The directory could not be created");
}
}
// This method ensures that there are the necessary files
// used to process a cleaning order
public void CheckDefaultFiles()
{
FileStream fsCustomers = null;
BinaryFormatter bfCustomers = new BinaryFormatter();
// The Customers.cst file will contain the
// information about the customers
string strFilename =
@"C:\Georgetown Cleaning Services\Customers.cst";
// When the application starts, if the list of
// customers doesn't (yet) exist, then create it
if (!File.Exists(strFilename))
{
Customers.Add(strPhoneNumber, strCustomerName);
try
{
fsCustomers = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write);
bfCustomers.Serialize(fsCustomers, Customers);
}
finally
{
fsCustomers.Close();
}
}
// The CleaningOrders.gco file will
// contain the cleaning orders
strFilename = @"C:\Georgetown Cleaning " +
@"Services\CleaningOrders.gco";
if (!File.Exists(strFilename))
{
FileStream fsCleaningOrders = null;
BinaryFormatter bfCleaningOrders =
new BinaryFormatter();
// This file will contain only useless default values
// Normally, this cleaning order should never be deleted
this.depot.ReceiptNumber = 0;
this.depot.CustomerName = strCustomerName;
this.depot.CustomerPhoneNumber = strPhoneNumber;
this.depot.OrderDate = new DateTime(1960, 1, 1);
this.depot.OrderTime = new DateTime(1960, 1, 1,
1, 1, 1);
this.depot.NumberOfShirts = 0;
this.depot.NumberOfPants = 0;
this.depot.NumberOtherItems = 0;
this.depot.PriceOneShirt = 0.00M;
this.depot.PriceAPairOfPants = 0.00M;
this.depot.PriceOtherItems = 0.00M;
this.depot.TaxRate = 0.00M; // 5.75%
this.depot.SubTotalShirts = 0;
this.depot.SubTotalPants = 0;
this.depot.SubTotalOtherItems = 0;
this.depot.TotalOrder = 0;
this.depot.TaxAmount = 0;
this.depot.SalesTotal = 0;
// After creating this default order,
// add it to the collection
this.CleaningOrders.Add(this.depot);
// After creating the cleaning order, save it
try
{
fsCleaningOrders = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write);
bfCleaningOrders.Serialize(fsCleaningOrders,
CleaningOrders);
}
finally
{
fsCleaningOrders.Close();
}
}
}
// This method is used to find out if the customer
// already exists in our database
private void IdentifyCustomer()
{
bool found = false;
string strTelephoneNumber = "000";
do
{
Console.Write("Enter Customer Phone Number: ");
strTelephoneNumber = Console.ReadLine();
// Remove the spaces, parentheses, and dashes, if any
strTelephoneNumber =
strTelephoneNumber.Replace(" ", "");
strTelephoneNumber =
strTelephoneNumber.Replace("(", "");
strTelephoneNumber =
strTelephoneNumber.Replace(")", "");
strTelephoneNumber =
strTelephoneNumber.Replace("-", "");
if (strTelephoneNumber.Length != 10)
{
// We will use a (small version of)
// Canada and US telephone numbers
Console.WriteLine("Invalid telphone number: " +
"you entered {0} " +
"characters instead of 10 digits",
strTelephoneNumber.Length);
}
} while (strTelephoneNumber.Length != 10);
// We will use the same formula for
// telephone numbers: (000) 000-0000
strPhoneNumber = "(" + strTelephoneNumber.Substring(0, 3) +
") " + strTelephoneNumber.Substring(3, 3) +
"-" + strTelephoneNumber.Substring(6, 4);
string strFilename =
@"C:\Georgetown Cleaning Services\Customers.cst";
if (File.Exists(strFilename))
{
FileStream fsCustomers = File.Open(strFilename,
FileMode.Open,
FileAccess.Read);
BinaryFormatter bfCustomers = new BinaryFormatter();
Customers = (Hashtable)bfCustomers.Deserialize(fsCustomers);
fsCustomers.Close();
foreach (DictionaryEntry de in Customers)
{
if ((string)de.Key == strPhoneNumber)
{
found = true;
strPhoneNumber = (string)de.Key;
strCustomerName = (string)de.Value;
}
}
if (found == true)
{
Console.WriteLine("\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("------------------------------------");
Console.WriteLine("Customer Name: {0}", strCustomerName);
Console.WriteLine("Phone Number: {0}", strPhoneNumber);
Console.WriteLine("------------------------------------\n");
}
else // If the customer information was not found in a file
{
Console.WriteLine("This is the first cleaning order " +
"of this customer");
FileStream fsCustomer = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write);
BinaryFormatter bfCustomer = new BinaryFormatter();
Console.Write("Enter Customer Name: ");
strCustomerName = Console.ReadLine();
Customers.Add(strPhoneNumber, strCustomerName);
bfCustomer.Serialize(fsCustomer, Customers);
fsCustomer.Close();
}
}
else
Console.WriteLine("The Customers list was not found");
}
public void ProcessOrder()
{
// These two pieces of information are used for money change
decimal AmountTended;
decimal Difference;
Console.WriteLine("-/- Georgetown Cleaning Services -/-");
this.IdentifyCustomer();
try
{
Console.Write("Enter the order date(mm/dd/yyyy): ");
this.depot.OrderDate = DateTime.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The value you entered is not a valid date");
}
try
{
Console.Write("Enter the order time(hh:mm AM/PM): ");
this.depot.OrderTime = DateTime.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("The value you entered is not a valid time");
}
// Request the quantity of each category of items
try
{
Console.Write("Number of Shirts: ");
this.depot.NumberOfShirts =
uint.Parse(Console.ReadLine());
if (this.depot.NumberOfShirts < uint.MinValue)
throw new OverflowException("Negative value not " +
"allowed for shirts");
}
catch (FormatException)
{
Console.WriteLine("The value you typed for the number of " +
"shirts is not a valid number");
}
try
{
Console.Write("Number of Pants: ");
this.depot.NumberOfPants =
uint.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The value you typed for the number of " +
"pair or pants is not a valid number");
}
try
{
Console.Write("Number of Other Items: ");
this.depot.NumberOtherItems = uint.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("The value you typed for the number of " +
"other items is not a valid number");
}
// Perform the necessary calculations
this.depot.SubTotalShirts =
this.depot.NumberOfShirts * this.depot.PriceOneShirt;
this.depot.SubTotalPants =
this.depot.NumberOfPants * this.depot.PriceAPairOfPants;
this.depot.SubTotalOtherItems =
this.depot.NumberOtherItems * this.depot.PriceOtherItems;
// Calculate the "temporary" total of the order
this.depot.TotalOrder = this.depot.SubTotalShirts +
this.depot.SubTotalPants +
this.depot.SubTotalOtherItems;
// Calculate the tax amount using a constant rate
this.depot.TaxAmount = this.depot.TotalOrder * this.depot.TaxRate;
// Add the tax amount to the total order
this.depot.SalesTotal = this.depot.TotalOrder + this.depot.TaxAmount;
// Communicate the total to the user...
Console.WriteLine("\nThe Total order is: {0:C}", this.depot.SalesTotal);
// and request money for the order
try
{
Console.Write("Amount Tended? ");
AmountTended = decimal.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("You were asked to enter an " +
"amount of money but...");
}
// Calculate the difference owed to the customer
// or that the customer still owes to the store
Difference = AmountTended - this.depot.SalesTotal;
this.PreviewReceipt();
this.SaveCleaningOrder();
}
public void PreviewReceipt()
{
Console.WriteLine();
// Display the receipt
Console.WriteLine("====================================");
Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("====================================");
Console.WriteLine("Customer: {0}", this.strCustomerName);
Console.WriteLine("Home Phone: {0}", this.strPhoneNumber);
Console.WriteLine("Order Date: {0:D}", this.depot.OrderDate);
Console.WriteLine("Order Time: {0:t}", this.depot.OrderTime);
Console.WriteLine("------------------------------------");
Console.WriteLine("Item Type Qty Unit/Price Sub-Total");
Console.WriteLine("------------------------------------");
Console.WriteLine("Shirts {0,3} {1,4} {2,6}",
this.depot.NumberOfShirts,
this.depot.PriceOneShirt,
this.depot.SubTotalShirts);
Console.WriteLine("Pants {0,3} {1,4} {2,6}",
this.depot.NumberOfPants,
this.depot.PriceAPairOfPants,
this.depot.SubTotalPants);
Console.WriteLine("Other Items {0,3} {1,4} {2,6}",
this.depot.NumberOtherItems,
this.depot.PriceOtherItems,
this.depot.SubTotalOtherItems);
Console.WriteLine("------------------------------------");
Console.WriteLine("Total Order: {0,6}",
this.depot.TotalOrder.ToString("C"));
Console.WriteLine("Tax Rate: {0,6}",
this.depot.TaxRate.ToString("P"));
Console.WriteLine("Tax Amount: {0,6}",
this.depot.TaxAmount.ToString("C"));
Console.WriteLine("Net Price: {0,6}",
this.depot.SalesTotal.ToString("C"));
Console.WriteLine("------------------------------------");
Console.WriteLine("Amount Tended: {0,6}",
AmountTended.ToString("C"));
Console.WriteLine("Difference: {0,6}",
Difference.ToString("C"));
Console.WriteLine("====================================");
}
public void SaveCleaningOrder()
{
int highReceiptNumber = 0;
FileStream fsCleaningOrders = null;
BinaryFormatter bfCleaningOrders = new BinaryFormatter();
string strFilename =
@"C:\Georgetown Cleaning Services\CleaningOrders.gco";
if (File.Exists(strFilename))
{
try
{
fsCleaningOrders = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read);
CleaningOrders =
(ArrayList)bfCleaningOrders.Deserialize(fsCleaningOrders);
}
finally
{
fsCleaningOrders.Close();
}
highReceiptNumber =
((CleaningOrderDetails)CleaningOrders[CleaningOrders.Count
- 1]).ReceiptNumber;
this.depot.ReceiptNumber = highReceiptNumber + 1;
this.depot.CustomerName = strCustomerName;
this.depot.CustomerPhoneNumber = strPhoneNumber;
this.CleaningOrders.Add(this.depot);
try
{
fsCleaningOrders = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write);
bfCleaningOrders.Serialize(fsCleaningOrders,
CleaningOrders);
}
finally
{
fsCleaningOrders.Close();
}
}
else
Console.WriteLine("The cleaning orders could " +
"not be retrieved");
}
public void OpenCleaningOrder()
{
bool foundReceipt = false;
try
{
Console.Write("Enter Receipt Number: ");
int recNumber = int.Parse(Console.ReadLine());
FileStream fsCleaningOrders = null;
BinaryFormatter bfCleaningOrders = new BinaryFormatter();
string strFilename =
@"C:\Georgetown Cleaning Services\CleaningOrders.gco";
if (File.Exists(strFilename))
{
try
{
fsCleaningOrders = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read);
CleaningOrders =
(ArrayList)bfCleaningOrders.Deserialize(fsCleaningOrders);
}
finally
{
fsCleaningOrders.Close();
}
foreach (CleaningOrderDetails cod in CleaningOrders)
{
if (cod.ReceiptNumber == recNumber)
{
foundReceipt = true;
// Display the
Console.WriteLine("====================================");
Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("====================================");
Console.WriteLine("Receipt #: {0}", cod.ReceiptNumber);
Console.WriteLine("Customer: {0}", cod.CustomerName);
Console.WriteLine("Home Phone: {0}",
cod.CustomerPhoneNumber);
Console.WriteLine("Order Date: {0:D}", cod.OrderDate);
Console.WriteLine("Order Time: {0:t}", cod.OrderTime);
Console.WriteLine("------------------------------------");
Console.WriteLine("Item Type Qty Unit/Price Sub-Total");
Console.WriteLine("------------------------------------");
Console.WriteLine("Shirts {0,3} {1,4} {2,6}",
cod.NumberOfShirts,
cod.PriceOneShirt,
cod.SubTotalShirts);
Console.WriteLine("Pants {0,3} {1,4} {2,6}",
cod.NumberOfPants,
cod.PriceAPairOfPants,
cod.SubTotalPants);
Console.WriteLine("Other Items {0,3} {1,4} {2,6}",
cod.NumberOtherItems,
cod.PriceOtherItems,
cod.SubTotalOtherItems);
Console.WriteLine("------------------------------------");
Console.WriteLine("Total Order: {0,6}",
cod.TotalOrder.ToString("C"));
Console.WriteLine("Tax Rate: {0,6}",
cod.TaxRate.ToString("P"));
Console.WriteLine("Tax Amount: {0,6}",
cod.TaxAmount.ToString("C"));
Console.WriteLine("Net Price: {0,6}",
cod.SalesTotal.ToString("C"));
Console.WriteLine("====================================");
return;
} // if found receipt number
}// foreach
if (foundReceipt == false)
Console.WriteLine("No cleaning order with that " +
"receipt number was found");
}// if file exists
else
Console.WriteLine("The cleaning orders were not found");
}
catch (FormatException)
{
Console.WriteLine("Invalid Choice");
}
}
}
}
|
- Access the Program.cs file and change it as follows:
using System;
namespace GeorgetownCleaningServicesHatch1
{
class Program
{
static int Main(string[] args)
{
char answer = 'q';
CleaningDeposit depotOrder = new CleaningDeposit();
do
{
Console.WriteLine("================================================");
Console.WriteLine("Georgetown Cleaning Services");
Console.WriteLine("================================================");
try
{
Console.WriteLine("What do you want to do?");
Console.WriteLine("1. Process a new cleaning order");
Console.WriteLine("2. Retrieve an existing order");
Console.WriteLine("0. Quit");
Console.Write("Your Choice: ");
answer = char.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Invalid Answer");
}
switch (answer)
{
case '1':
depotOrder.ProcessOrder();
break;
case '2':
depotOrder.OpenCleaningOrder();
break;
default:
break;
}
} while ((answer == '1') ||
(answer == '2'));
Console.WriteLine();
return 0;
}
}
}
|
- Execute the application to test it
- First create a few customers
- Then process a few orders:
- The open a previously created order
- Close the DOS window
Locating an Item in a Hash Table
|
|
Locating an item in a hash table consists of looking for
either a key, a value, or a combination of Key=Value. The Hashtable
class is equipped to handle these operations with little effort on your part. If
you know the key of an item but want to find a value, you can use the index
property because it produces it. Here is an example:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
Chelsea20062007["Claude"] = "Makelele";
string Value = (string)Chelsea20062007["Didier"];
Console.WriteLine("The value of the Didier key is {0}",
Value);
Console.WriteLine();
return 0;
}
}
}
This would produce:
The value of the Didier key is Drogba
Press any key to continue . . .
To find out whether a Key=Value item exists in the list, you
can call the Contains() method. Its syntax is:
public virtual bool Contains(object key);
To look for an item, you pass its key as argument to this
method. Here is an example:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
Chelsea20062007["Claude"] = "Makelele";
Console.WriteLine("List of items");
foreach (DictionaryEntry entry in Chelsea20062007)
Console.WriteLine("{0} {1}", entry.Key, entry.Value);
bool found = Chelsea20062007.Contains("Claude");
if (found == true)
Console.WriteLine("\nThe list contains an item " +
"whose key is Claude");
else
Console.WriteLine("\nThe list doesn't contain an " +
"item whose key is Claude");
found = Chelsea20062007.Contains("James");
if (found == true)
Console.WriteLine("\nThe list contains an item " +
"whose key is Claude");
else
Console.WriteLine("\nThe list doesn't contain an " +
"item whose key is James");
Console.WriteLine();
return 0;
}
}
}
This would produce:
List of items
Didier Drogba
Michael Ballack
Claude Makelele
The list contains an item whose key is Claude
The list doesn't contain an item whose key is James
Press any key to continue . . .
To find out whether a particular key exists in the list, you
can call the ContainsKey() method whose syntax is:
public virtual bool ContainsKey(object key);
To find out whether a particular key exists in the list, you
can call the ContainsKey() method whose syntax is:
public virtual bool ContainsValue(object key);
When calling this method, pass a Value value as
argument. Here is an example:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
Chelsea20062007["Claude"] = "Makelele";
Console.WriteLine("List of items");
foreach (DictionaryEntry entry in Chelsea20062007)
Console.WriteLine("{0} {1}", entry.Key, entry.Value);
bool found = Chelsea20062007.ContainsValue("Makelele");
if (found == true)
Console.WriteLine("\nMakelele plays for Chelsea");
else
Console.WriteLine("\nMakelele doesn't plays for Chelsea");
found = Chelsea20062007.ContainsValue("Fortune");
if (found == true)
Console.WriteLine("\nRonaldinho plays for Chelsea");
else
Console.WriteLine("\nRonaldinho doesn't plays for Chelsea");
Console.WriteLine();
return 0;
}
}
}
This would produce:
List of items
Didier Drogba
Michael Ballack
Claude Makelele
Makele plays for Chelsea
Ronaldinho doesn't plays for Chelsea
Press any key to continue . . .
Removing Items From a Hash Table
|
|
To delete one item from the list, you can call the Remove()
method. Its syntax is:
public virtual void Remove(object key);
Here is an example:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
Chelsea20062007["Claude"] = "Makelele";
Console.WriteLine("List of items");
foreach (DictionaryEntry entry in Chelsea20062007)
Console.WriteLine("{0} {1}", entry.Key, entry.Value);
Chelsea20062007.Remove("Didier");
Console.WriteLine("\nThe item that contains " +
"Didier has been removed\n");
Console.WriteLine("List of items");
foreach (DictionaryEntry entry in Chelsea20062007)
Console.WriteLine("{0} {1}", entry.Key, entry.Value);
Console.WriteLine();
return 0;
}
}
}
This would produce:
List of items
Didier Drogba
Michael Ballack
Claude Makelele
The item that contains Didier has been removed
List of items
Michael Ballack
Claude Makelele
Press any key to continue . . .
To delete all items from the list, you can call the Clear()
method. Its syntax is:
public virtual void Clear();
This is an example:
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
Hashtable Chelsea20062007 = new Hashtable();
Chelsea20062007.Add("Michael", "Ballack");
Chelsea20062007.Add("Didier", "Drogba");
Chelsea20062007["Claude"] = "Makelele";
Console.WriteLine("List of items");
foreach (DictionaryEntry entry in Chelsea20062007)
Console.WriteLine("{0} {1}", entry.Key, entry.Value);
Chelsea20062007.Clear();
Console.WriteLine("\nThe list is now empty!");
Console.WriteLine("List of items");
foreach (DictionaryEntry entry in Chelsea20062007)
Console.WriteLine("{0} {1}", entry.Key, entry.Value);
Console.WriteLine();
return 0;
}
}
}
This would produce:
List of items
Didier Drogba
Michael Ballack
Claude Makelele
The list is now empty!
List of items
Press any key to continue . . .
|
|