Home

Built-In Collection Classes

 

Hash Tables

 

Introduction

If you have been playing a little deeper with Microsoft Windows for a while, you are probably familiar with objects referred to as initialization files or ini files. These are files whose contents are made of lines that each displays a combination of a right value assigned to a left value. Here is an example:

PROJECT=AIOCPE
MANUFACTURER=HP
Wrapper=1
DEFAULT=1
LOG_DISABLED=0
LOG_ERROR=1
LOG_WARNING=2
LOG_MAINTRACE=4
LOG_DETAILEDTRACE=8
FILESIZE=524288

A hash table is list of items that each (item) is made of a right object assigned to a left object. The object on the left side is called a key. The object on the right side is called a value. Based on this, an item of a hash table is in the form:

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 LearningPractical Learning: Introducing Hash Tables

  1. Create a new Console Application named GeorgetownCleaningServices8
  2. To save the project, on the Standard toolbar, click the Save All button
  3. Accept all the defaults and click Save
  4. To cre ate a new class, on the main menu, click Project -> Add Class...
  5. Set the Name to CleaningOrderDetails and click Add
  6. 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;
        }
    }
  7. Save the file

Creating a Hash Table

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), and 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 list, 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 cannot 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 compiler 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 LearningPractical Learning: Using a Hash Table

  1. To create a new class, in the Class View, right-click GeorgetownCleaningServices8 -> Add -> Class...
  2. Set the Name to Customers and press Enter
  3. Change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices8
    {
        [Serializable]
        public class Customer
        {
            public string Name;
            public string PhoneNumber;
        }
    }
  4. To create a new class, in the Solution Explorer, right-click GeorgetownCleaningServices8 -> Add -> Class...
  5. Set the Name to CleaningOrderManagement and click Add
  6. Change the file as follows:
     
    using System;
    using System.IO;
    using System.Collections;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace GeorgetownCleaningServices8
    {
        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");
                }
            }
        }
    }
  7. 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;
            }
        }
    }
  8. Execute the application to test it
  9. First create a few customers
  10. Then process a few orders:
  11. The open a previously created order 
  12. 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 . . .

Stacks

 

Introduction

A stack is a technique of creating a list so that the last item added to the list is also the first one that can be removed. It can be illustrated as placing a few cups in a box that can receive only one on top of another (no adjacent cup). When it comes time to get one of those cups, you must first access the last one that was added. This technique of building a list is referred to as first-in last-out (FILO).

To support stack types of collections, the .NET Framework provides the Stack class. Stack is a serializable class that implements the ICollection (giving the ability to know the number of items in the list) and the IEnumerable (which gives the ability to use foreach).

Creating a Stack

The Stack class is equipped with three constructors. The default constructor allows you to create a stack without primarily taking any action. Here is an example:

using System;
using System.Collections;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Stack players = new Stack();

        return 0;
    }
}

If you create a stack with this constructor, the list is primarily empty with a default capacity. If you want, before initializing the list, you can specify how much space the compiler should primarily allocate for the number of eventual items of the list. To provide this information, the Stack class is equipped with the following constructor:

public Stack(int initialCapacity);

Adding Items to a Stack

To add an item to a stack, you can call the Push() method of the Stack class. Its syntax is:

public virtual void Push(object obj);

The new item is passed as argument to the method. Here is an example:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Stack players = new Stack();
        Sport basketball = new Sport();

        basketball.Name = "Basketball";
        basketball.PlayersPerTeam = 5;
        players.Push(basketball);

        SaveSports(players);
        return 0;
    }

    public static void SaveSports(Stack stc)
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfSport = new BinaryFormatter();

        bfSport.Serialize(fsSport, stc);
        fsSport.Close();
    }
}

Whenever you add a new item to the stack, the compiler increases the number of items in the list. This number is stored in the Count property of the Stack class.

If you have a series of items that were created using a class that implements the ICollection interface, you can use the following constructor of the Stack class:

public Stack(ICollection col);

 When using this constructor, pass a variable of collection class as argument. Here is an example:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Sport spt = new Sport();
        ArrayList lstSports = new ArrayList();

        spt.Name = "Volleyball";
        spt.PlayersPerTeam = 6;
        lstSports.Add(spt);

        spt = new Sport();
        spt.Name = "Tennis Single";
        spt.PlayersPerTeam = 1;
        lstSports.Add(spt);

        spt = new Sport();
        spt.Name = "Handball";
        spt.PlayersPerTeam = 6;
        lstSports.Add(spt);

        Stack sports = new Stack(lstSports);

        SaveSports(sports);
        return 0;
    }

    public static void SaveSports(Stack stc)
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfSport = new BinaryFormatter();

        bfSport.Serialize(fsSport, stc);
        fsSport.Close();
    }
}

Accessing an Item in the Stack

As mentioned previously, the Stack class overrides the GetEnumerator() method by implementing the IEnumerable interface. This allows you to access each member of the stack using the foreach loop. Here is an example:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Stack sports = OpenSports();

        foreach (Sport spt in sports)
        {
            Console.WriteLine("=-+-+-+-+-= Sport =-+-+-+-+-=");
            Console.WriteLine("Sport Name:   {0}", spt.Name);
            Console.WriteLine("Players/Team: {0}", spt.PlayersPerTeam);
        }

        Console.WriteLine();
        return 0;
    }

    public static void SaveSports(Stack stc)
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfSport = new BinaryFormatter();

        bfSport.Serialize(fsSport, stc);
        fsSport.Close();
    }

    public static Stack OpenSports()
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Open,
                                            FileAccess.Read);
        BinaryFormatter bfSport = new BinaryFormatter();

        Stack games = (Stack)bfSport.Deserialize(fsSport);
        fsSport.Close();

        return games;
    }
}

To find out if the list contains a particular item, you can call the Contains() method of the Stack class. Its syntax is:

public virtual bool Contains(object obj);

Removing Items From a Stack

As mentioned earlier, a stack is organized so that the last item that was added to the list is the first one to be removed. To support this operation, the Stack class is equipped with the Pop() method. Its syntax is:

public virtual object Pop();

When called, this method removed the last item in the stack. If you are interested to know what item was removed, this method returns it as an Object value.

Here is an example of calling the method:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Stack sports = OpenSports();

        foreach (Sport spt in sports)
        {
            Console.WriteLine("=-+-+-+-+-= Sport =-+-+-+-+-=");
            Console.WriteLine("Sport Name:   {0}", spt.Name);
            Console.WriteLine("Players/Team: {0}", spt.PlayersPerTeam);
        }

        Sport  one = (Sport)sports.Pop();

        Console.WriteLine("The sport removed was");
        Console.WriteLine("=-+-+-+-+-= Sport =-+-+-+-+-=");
        Console.WriteLine("Sport Name:   {0}", one.Name);
        Console.WriteLine("Players/Team: {0}", one.PlayersPerTeam);

        SaveSports(sports);
        sports = OpenSports();

        Console.WriteLine("=====================================");
        foreach (Sport spt in sports)
        {
            Console.WriteLine("Sport Name:   {0}", spt.Name);
            Console.WriteLine("Players/Team: {0}", spt.PlayersPerTeam);
            Console.WriteLine("=-+-+-+-+-= Sport =-+-+-+-+-=");
        }
        
        Console.WriteLine();
        return 0;
    }

    public static void SaveSports(Stack stc)
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfSport = new BinaryFormatter();

        bfSport.Serialize(fsSport, stc);
        fsSport.Close();
    }

    public static Stack OpenSports()
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Open,
                                            FileAccess.Read);
        BinaryFormatter bfSport = new BinaryFormatter();

        Stack games = (Stack)bfSport.Deserialize(fsSport);
        fsSport.Close();

        return games;
    }
}

The Pop() method is used to remove one item from the stack. To remove all items from the list, you can call the Clear() method whose syntax is:

public virtual void Clear();

Queue

 

Introduction

A queue is a technique of using a list so that the first item added to the list will be the first one to be removed. This is referred to as first-in first-out (FIFO). To illustrate it, when people stand in line at one cashier of a supermarket, the first customer in line in front of the cashier will be the first to be served and the first to leave the supermarket.

To support queues, the .NET Framework provides the serialized Queue class that implements both the ICollection and the IEnumerable interfaces.

Creating a Queue

To create a queue, you can declare a Queue variable using one of its four constructors. The default constructor allows you to start a list without primarily adding an item to it. Here is an example:

public static class Program
{
    public static int Main(string[] args)
    {
        Queue que = new Queue();

        return 0;
    }
}

After this declaration, the compiler reserves some default memory space for the variable. If you want to specify how much space should be primarily allocated for the variable, you can use the following constructor:

public Queue(int capacity);

Building a Queue

The action that consists of adding an item to the queue is called "enqueue". To perform this operation, you can call the Queue.Enqueue() method whose syntax is:

public virtual void Enqueue(object obj);

This method takes as argument the object you want to add to the queue and places it as the first candidate to be removed. Here are examples of calling the method:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

public enum Majors
{
    English,
    Nursing,
    Accounting,
    ComputerSciences,
    BusinessManagement,
    MathematicalSciences,
    HumanResourceDevelopment
}

[Serializable]
public class Student
{
    public string FullName;
    public DateTime DateOfBirth;
    public Majors Major;
}

public static class Program
{
    public static int Main(string[] args)
    {
        Queue que = new Queue();
        Student std = null;

        std = new Student();
        std.FullName = "Donald Palau";
        std.DateOfBirth = new DateTime(1988, 5, 12);
        std.Major = Majors.ComputerSciences;
        que.Enqueue(std);

        std = new Student();
        std.FullName = "Arlene Kafka";
        std.DateOfBirth = new DateTime(1992, 8, 4);
        std.Major = Majors.BusinessManagement;
        que.Enqueue(std);

        std = new Student();
        std.FullName = "Hortense Moons";
        std.DateOfBirth = new DateTime(1994, 10, 7);
        std.Major = Majors.MathematicalSciences;
        que.Enqueue(std);

        SaveStudents(que);
        return 0;
    }

    public static void SaveStudents(Queue q)
    {
        FileStream fsStudent = new FileStream("Students.roh",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfStudent = new BinaryFormatter();

        bfStudent.Serialize(fsStudent, q);
        fsStudent.Close();
    }

    public static Queue OpenStudents()
    {
        FileStream fsStudent = new FileStream("Students.roh",
                                            FileMode.Open,
                                            FileAccess.Read);
        BinaryFormatter bfStudent = new BinaryFormatter();

        Queue pupils = (Queue)bfStudent.Deserialize(fsStudent);
        fsStudent.Close();

        return pupils;
    }
}

If you already have a list created from a class that implements the ICollection interface, you can create a queue based on that list. To do this, you would use the following constructor of the Queue class:

public Queue(ICollection col);

This constructor accepts an ICollection implementer as argument. Here is an example:

using System;

public enum Majors
{
    English,
    Nursing,
    Accounting,
    ComputerSciences,
    BusinessManagement,
    MathematicalSciences,
    HumanResourceDevelopment
}

public class Student
{
    public string FullName;
    public DateTime DateOfBirth;
    public Majors Major;
}

public static class Program
{
    public static int Main(string[] args)
    {
        Student std = null;
        ArrayList lstStudents = new ArrayList();

        std = new Student();
        std.FullName = "Hermine Justice";
        std.DateOfBirth = new DateTime(1990, 3, 24);
        std.Major = Majors.English;
        lstStudents.Add(std);

        std = new Student();
        std.FullName = "Patricia Palermo";
        std.DateOfBirth = new DateTime(1989, 12, 20);
        std.Major = Majors.BusinessManagement;
        lstStudents.Add(std);

        Queue que = new Queue(lstStudents);
        
        return 0;
    }
}

Retrieving the Items From a Queue

Remember that the first item added to a queue stays in front of all others that would be added. To get (only) the first item of a queue, the Queue class is equipped with a method named Peek(). Its syntax is:

public virtual object Peek();

This method returns an Object object that represents the first item of the queue (remember to cast it to your particular object if necessary). Here are two examples of calling it:

using System;
using System.Collections;

public enum Majors
{
    English,
    Nursing,
    Accounting,
    ComputerSciences,
    BusinessManagement,
    MathematicalSciences,
    HumanResourceDevelopment
}

public class Student
{
    public string FullName;
    public DateTime DateOfBirth;
    public Majors Major;
}

public static class Program
{
    public static int Main(string[] args)
    {
        Queue que = new Queue();
        Student std = null;

        std = new Student();
        std.FullName = "Donald Palau";
        std.DateOfBirth = new DateTime(1988, 5, 12);
        std.Major = Majors.ComputerSciences;
        que.Enqueue(std);

        std = new Student();
        std.FullName = "Arlene Kafka";
        std.DateOfBirth = new DateTime(1992, 8, 4);
        std.Major = Majors.BusinessManagement;
        que.Enqueue(std);

        Console.WriteLine("The current first item of the queue is");
        Student s1 = (Student)que.Peek();
        Console.WriteLine("== Student Information ==");
        Console.WriteLine("Full Name:     {0}", s1.FullName);
        Console.WriteLine("Date of Birth: {0:d}", s1.DateOfBirth);
        Console.Write("Major:         ");
        switch (s1.Major)
        {
            case Majors.English:
                Console.WriteLine("English");
                break;
            case Majors.Nursing:
                Console.WriteLine("Nursing");
                break;
            case Majors.Accounting:
                Console.WriteLine("Accounting");
                break;
            case Majors.ComputerSciences:
                Console.WriteLine("Computer Sciences");
                break;
            case Majors.BusinessManagement:
                Console.WriteLine("Business Management");
                break;
            case Majors.MathematicalSciences:
                Console.WriteLine("Mathematical Sciences");
                break;
            case Majors.HumanResourceDevelopment:
                Console.WriteLine("Human Resource Development");
                break;
        }

        Console.WriteLine("--------------------------------------------");

        std = new Student();
        std.FullName = "Hortense Moons";
        std.DateOfBirth = new DateTime(1994, 10, 7);
        std.Major = Majors.MathematicalSciences;
        que.Enqueue(std);

        Console.WriteLine("The current first item of the queue is");
        Student s2 = (Student)que.Peek();
        Console.WriteLine("== Student Information ==");
        Console.WriteLine("Full Name:     {0}", s2.FullName);
        Console.WriteLine("Date of Birth: {0:d}", s2.DateOfBirth);
        Console.Write("Major:         ");
        switch (s2.Major)
        {
            case Majors.English:
                Console.WriteLine("English");
                break;
            case Majors.Nursing:
                Console.WriteLine("Nursing");
                break;
            case Majors.Accounting:
                Console.WriteLine("Accounting");
                break;
            case Majors.ComputerSciences:
                Console.WriteLine("Computer Sciences");
                break;
            case Majors.BusinessManagement:
                Console.WriteLine("Business Management");
                break;
            case Majors.MathematicalSciences:
                Console.WriteLine("Mathematical Sciences");
                break;
            case Majors.HumanResourceDevelopment:
                Console.WriteLine("Human Resource Development");
                break;
        }

        Console.WriteLine("--------------------------------------------");

        return 0;
    }
}

This would produce:

The current first item of the queue is
== Student Information ==
Full Name:     Donald Palau
Date of Birth: 5/12/1988
Major:         Computer Sciences
--------------------------------------------
The current first item of the queue is
== Student Information ==
Full Name:     Donald Palau
Date of Birth: 5/12/1988
Major:         Computer Sciences
--------------------------------------------
Press any key to continue . . .

To give you access to the items of a queue, the Queue class overrides the GetEnumerator() method of the IEnumerable class that it implements. This allows you to use the foreach loop to continuously enumerate the members of a queue. Here is an example:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

public enum Majors
{
    English,
    Nursing,
    Accounting,
    ComputerSciences,
    BusinessManagement,
    MathematicalSciences,
    HumanResourceDevelopment
}

[Serializable]
public class Student
{
    public string FullName;
    public DateTime DateOfBirth;
    public Majors Major;
}

public static class Program
{
    public static int Main(string[] args)
    {
        Student std = null;
        Queue lstStudents = OpenStudents();

        std = new Student();
        std.FullName = "Hermine Justice";
        std.DateOfBirth = new DateTime(1990, 3, 24);
        std.Major = Majors.English;
        lstStudents.Enqueue(std);

        std = new Student();
        std.FullName = "Patricia Palermo";
        std.DateOfBirth = new DateTime(1989, 12, 20);
        std.Major = Majors.BusinessManagement;
        lstStudents.Enqueue(std);

        SaveStudents(lstStudents);
        lstStudents = OpenStudents();
        ShowStudents(lstStudents);

        return 0;
    }

    public static void ShowStudents(Queue q)
    {
        foreach (Student s in q)
        {
            Console.WriteLine("== Student Information ==");
            Console.WriteLine("Full Name:     {0}", s.FullName);
            Console.WriteLine("Date of Birth: {0:d}", s.DateOfBirth);
            Console.Write("Major:         ");
            switch (s.Major)
            {
                case Majors.English:
                    Console.WriteLine("English");
                    break;
                case Majors.Nursing:
                    Console.WriteLine("Nursing");
                    break;
                case Majors.Accounting:
                    Console.WriteLine("Accounting");
                    break;
                case Majors.ComputerSciences:
                    Console.WriteLine("Computer Sciences");
                    break;
                case Majors.BusinessManagement:
                    Console.WriteLine("Business Management");
                    break;
                case Majors.MathematicalSciences:
                    Console.WriteLine("Mathematical Sciences");
                    break;
                case Majors.HumanResourceDevelopment:
                    Console.WriteLine("Human Resource Development");
                    break;
            }

            Console.WriteLine("--------------------------------------------");
        }
    }

    public static void SaveStudents(Queue q)
    {
        FileStream fsStudent = new FileStream("Students.roh",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfStudent = new BinaryFormatter();

        bfStudent.Serialize(fsStudent, q);
        fsStudent.Close();
    }

    public static Queue OpenStudents()
    {
        FileStream fsStudent = new FileStream("Students.roh",
                                            FileMode.Open,
                                            FileAccess.Read);
        BinaryFormatter bfStudent = new BinaryFormatter();

        Queue pupils = (Queue)bfStudent.Deserialize(fsStudent);
        fsStudent.Close();

        return pupils;
    }
}

This would produce:

== Student Information ==
Full Name:     Donald Palau
Date of Birth: 5/12/1988
Major:         Computer Sciences
--------------------------------------------
== Student Information ==
Full Name:     Arlene Kafka
Date of Birth: 8/4/1992
Major:         Business Management
--------------------------------------------
== Student Information ==
Full Name:     Hortense Moons
Date of Birth: 10/7/1994
Major:         Mathematical Sciences
--------------------------------------------
== Student Information ==
Full Name:     Hermine Justice
Date of Birth: 3/24/1990
Major:         English
--------------------------------------------
== Student Information ==
Full Name:     Patricia Palermo
Date of Birth: 12/20/1989
Major:         Business Management
--------------------------------------------
Press any key to continue . . .

Removing Items From a Queue

The process of removing an item from a queue is called "dequeue". To assist you with performing this operation, the Queue class is equipped with a method named Dequeue. Its syntax is:

public virtual object Dequeue();

The primary purpose of this method is to delete the first item of the Queue list. If you are interested to know what item was deleted, this method returns it.

To remove all items from the queue, you can call the Clear() method of the class. Its syntax is:

public virtual void Clear();

 

 

 

Previous Copyright © 2008-2016, FunctionX, Inc. Next