Home

A Collection of Items

 

Introduction

We should already know how to create an array as a list of items. Like an array, a collection is a series of items of the same type. The particularity with creating an array is that you must know in advance the number of items that will make up the list. There are times when you don't know, you can't know, or you can't predict the number of items of the list. For this reason, you may want to create the list for which you don't specify the maximum number of items but you allow the user of the list to add, locate, or remove items at will.

Before creating a list, you probably should first decide or define what the list would be made of. As different as they are, one list can be made of numeric values. For example, a list that will be made of numbers. You may want a list that is made of names. Such a list can be created from a class that includes a string member variable. Another type of list can contain complex objects.

Practical LearningPractical Learning: Introducing Collections

  1. Start Microsoft Visual C# and create a new Console Application named FlowerShop4
  2. To save the project, on the Standard toolbar, click the Save All button
  3. Accept all defaults and click Save
  4. To create a new class, in the Solution Explorer, right-click FlowerShop4 -> Add -> Class...
  5. Set the Name of the class to Flower and click Add
  6. Change the file as follows:
     
    using System;
    
    namespace FlowerShop4
    {
        public enum FlowerType
        {
            Roses = 1,
            Lilies,
            Daisies,
            Carnations,
            LivePlant,
            Mixed
        }
    
        public enum FlowerColor
        {
            Red = 1,
            White,
            Yellow,
            Pink,
            Orange,
            Blue,
            Lavender,
            Mixed
        }
    
        public enum FlowerArrangement
        {
            Bouquet = 1,
            Vase,
            Basket,
            Any
        }
    
        public sealed class Flower
        {
            private decimal pc;
            public FlowerType Type;
            public FlowerColor Color;
            public FlowerArrangement Arrangement;
    
            public Flower()
            {
                Type = FlowerType.Mixed;
                Color = FlowerColor.Mixed;
                Arrangement = FlowerArrangement.Vase;
                pc = 0.00M;
            }
    
            public Flower(FlowerType type, FlowerColor color,
                    FlowerArrangement argn, decimal price)
            {
                Type = type;
                Color = color;
                Arrangement = argn;
                pc = price;
            }
    
            public decimal UnitPrice
            {
                get { return pc; }
                set { pc = value; }
            }
        }
    }
  7. To create a new class, in the Solution Explorer, right-click FlowerShop4 -> Add -> Class...
  8. Set the Name of the class to OrderProcessing and click Add
  9. Complete the OrderProcessing.cs file as follows:
     
    using System;
    
    namespace FlowerShop4
    {
        public class OrderProcessing
        {
            public Flower FlowerOrder;
            private int qty;
    
            public int Quantity
            {
                get { return qty; }
                set { qty = value; }
            }
    
            public OrderProcessing()
            {
                FlowerOrder = new Flower();
            }
    
            public decimal TotalPrice
            {
                get { return Quantity * FlowerOrder.UnitPrice; }
            }
    
            public void GetFlowerType()
            {
                int choice = 0;
    
                do
                {
                    try
                    {
                        Console.WriteLine("Enter the Type of Flower Order");
                        Console.WriteLine("1. Roses");
                        Console.WriteLine("2. Lilies");
                        Console.WriteLine("3. Daisies");
                        Console.WriteLine("4. Carnations");
                        Console.WriteLine("5. Live Plant");
                        Console.WriteLine("6. Mixed");
                        Console.Write("Your Choice: ");
                        choice = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You failed to enter an " +
                                          "appropriate number!");
                    }
    
                    if ((choice < 1) || (choice > 6))
                        Console.WriteLine("Invalid Value: Please enter " +
                                          "a value between 1 and 6");
                } while ((choice < 1) || (choice > 6));
    
                switch (choice)
                {
                    case 1:
                        FlowerOrder.Type = FlowerType.Roses;
                        break;
                    case 2:
                        FlowerOrder.Type = FlowerType.Lilies;
                        break;
                    case 3:
                        FlowerOrder.Type = FlowerType.Daisies;
                        break;
                    case 4:
                        FlowerOrder.Type = FlowerType.Carnations;
                        break;
                    case 5:
                        FlowerOrder.Type = FlowerType.LivePlant;
                        break;
                    default:
                        FlowerOrder.Type = FlowerType.Mixed;
                        break;
                }
            }
    
            public void GetFlowerColor()
            {
                int choice = 0;
    
                do
                {
                    try
                    {
                        Console.WriteLine("Enter the Color");
                        Console.WriteLine("1. Red");
                        Console.WriteLine("2. White");
                        Console.WriteLine("3. Yellow");
                        Console.WriteLine("4. Pink");
                        Console.WriteLine("5. Orange");
                        Console.WriteLine("6. Blue");
                        Console.WriteLine("7. Lavender");
                        Console.WriteLine("8. Mixed");
                        Console.Write("Your Choice: ");
                        choice = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You didn't enter an " +
                                          "appropriate number!");
                    }
    
                    if ((choice < 1) || (choice > 8))
                        Console.WriteLine("Invalid Value: Please " +
                                          "enter a value between 1 and 8");
                } while ((choice < 1) || (choice > 8));
    
                switch (choice)
                {
                    case 1:
                        FlowerOrder.Color = FlowerColor.Red;
                        break;
                    case 2:
                        FlowerOrder.Color = FlowerColor.White;
                        break;
                    case 3:
                        FlowerOrder.Color = FlowerColor.Yellow;
                        break;
                    case 4:
                        FlowerOrder.Color = FlowerColor.Pink;
                        break;
                    case 5:
                        FlowerOrder.Color = FlowerColor.Yellow;
                        break;
                    case 6:
                        FlowerOrder.Color = FlowerColor.Blue;
                        break;
                    case 7:
                        FlowerOrder.Color = FlowerColor.Lavender;
                        break;
                    default:
                        FlowerOrder.Color = FlowerColor.Mixed;
                        break;
                }
            }
    
            public void GetFlowerArrangement()
            {
                int choice = 0;
    
                do
                {
                    try
                    {
                        Console.WriteLine("Enter the Type of Arrangement");
                        Console.WriteLine("1. Bouquet");
                        Console.WriteLine("2. Vase");
                        Console.WriteLine("3. Basket");
                        Console.WriteLine("4. Mixed");
                        Console.Write("Your Choice: ");
                        choice = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You didn't provide an " +
                                          "acceptable number!");
                    }
    
                    if ((choice < 1) || (choice > 4))
                        Console.WriteLine("Invalid Value: Please enter " +
                                          "a value between 1 and 4");
                } while ((choice < 1) || (choice > 4));
    
                switch (choice)
                {
                    case 1:
                        FlowerOrder.Arrangement = FlowerArrangement.Bouquet;
                        break;
                    case 2:
                        FlowerOrder.Arrangement = FlowerArrangement.Vase;
                        break;
                    case 3:
                        FlowerOrder.Arrangement = FlowerArrangement.Basket;
                        break;
                    default:
                        FlowerOrder.Arrangement = FlowerArrangement.Any;
                        break;
                }
            }
    
            public void ProcessOrder()
            {
                GetFlowerType();
                GetFlowerColor();
                GetFlowerArrangement();
    
                try
                {
                    Console.Write("Enter the Unit Price: ");
                    FlowerOrder.UnitPrice = 
                        Math.Abs(decimal.Parse(Console.ReadLine()));
                }
                catch (FormatException)
                {
                    Console.WriteLine("You didn't specify a valid price!");
                }
    
                try
                {
                    Console.Write("Enter Quantity:       ");
                    Quantity = Math.Abs(int.Parse(Console.ReadLine()));
                }
                catch (FormatException)
                {
                    Console.WriteLine("The quantity you entered " +
                                      "is not acceptable!");
                }
            }
    
            public void ShowOrder()
            {
                Console.WriteLine("=======================");
                Console.WriteLine("==-=-=Flower Shop=-=-==");
                Console.WriteLine("-----------------------");
                Console.WriteLine("Flower Type:  {0}", 
                    FlowerOrder.Type);
                Console.WriteLine("Flower Color: {0}", 
                    FlowerOrder.Color);
                Console.WriteLine("Arrangement:  {0}",
                    FlowerOrder.Arrangement);
                Console.WriteLine("Price:        {0:C}",
                    FlowerOrder.UnitPrice);
                Console.WriteLine("Quantity:     {0}", Quantity);
                Console.WriteLine("Total Price:  {0:C}", TotalPrice);
                Console.WriteLine("=======================");
            }
        }
    }
  10. Access the Program.cs file and complete it as follows:
     
    using System;
    
    namespace FlowerShop4
    {
        public class Program
        {
            static int Main(string[] args)
            {
                OrderProcessing order = new OrderProcessing();
    
                order.ProcessOrder();
                Console.WriteLine();
    
                order.ShowOrder();
                Console.WriteLine();
                return 0;
            }
        }
    }
  11. Execute the application and test it. Here is an example:
     
    Enter the Type of Flower Order
    1. Roses
    2. Lilies
    3. Daisies
    4. Carnations
    5. Live Plant
    6. Mixed
    Your Choice: 3
    Enter the Color
    1. Red
    2. White
    3. Yellow
    4. Pink
    5. Orange
    6. Blue
    7. Lavender
    8. Mixed
    Your Choice: 8
    Enter the Type of Arrangement
    1. Bouquet
    2. Vase
    3. Basket
    4. Mixed
    Your Choice: 1
    Enter the Unit Price: 45.50
    Enter Quantity:       3
    
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Flower Type:  Daisies
    Flower Color: Mixed
    Arrangement:  Bouquet
    Price:        $45.50
    Quantity:     3
    Total Price:  $136.50
    =======================
    
    Press any key to continue . . .
  12. Close the DOS window

Implementing a Collection

After deciding what each item of the list would be made of, you can create a class that would manage the list. This class would be responsible for all operations that can be performed on the list. If the list will be made of primitive values, you can directly a field of the desired type. Here is an example:

using System;

public class Numbers
{
    public double Number;
}

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

        return 0;
    }
}

If the list will be made of objects, you can first create a class that specifies those types of items and then declare its variable in the list class. Here is an example of a simple class that holds a double-precision value:

using System;

public class Number
{
    public double Item;
}

public class Numbers
{
    Number Sample;
}

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

        return 0;
    }
}

When creating a list, one of the aspects you should pay attention to is to keep track of the number of items in the list. To do this, you can create a property that holds the number. The value of this property would increase as the items are added to the list and the value would decrease as the items are removed from the list. Here is how this can be done:

using System;

public class Number
{
    public double Item;
}

public class Numbers
{
    int size;
    Number Sample;

    public Numbers()
    {
        size = 0;
    }

    public int Count
    {
        get { return size; }
    }
}

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

        Console.WriteLine("Number of Items: {0}", nbrs.Count);

        return 0;
    }
}

This would produce:

Number of Items: 0
Press any key to continue . . .

Practical LearningPractical Learning: Creating a Class Collection

  1. To create a new class, in the Class View, right-click FlowerShop4 -> Add -> Class...
  2. Set the Name to FlowerInventory and click Add
  3. Change the class as follows:
     
    using System;
    
    namespace FlowerShop4
    {
        public abstract class AFlower
        {
            protected int items;
    
            public AFlower()
            {
                items = 0;
            }
    
            public int Count
            {
                get { return items; }
            }
        }
    
        public class FlowerInventory : AFlower
        {
            public Flower Inventory;
    
            public FlowerInventory()
            {
            }
        }
    }
  4. Save the file

The Beginning of a Collection

A good collection is a list that can grow or shrink as the user wishes. When creating the list, you don't need to predict the maximum number of items that will be added to the list. When a list starts, it is empty or at least it must be considered like that, before any item is added to it. To specify this, you should declare a primary member variable. Although you can call it anything, it is usually called Head. This member can be made private if you don't intend to access it outside of the class. If you want clients of the class to access it, you can make it public. Here is an example:

public class Numbers
{
    int listSize;
    Number Sample;

    public Numbers()
    {
        size = 0;
        Head = null;
    }

    public int Count
    {
        get { return listSize; }
    }

    public Number Head;
}

Linking the Items of a Collection

We saw that when using an array, each member can be accessed using its index. If the items of a collection are not indexed, you must provide a mechanism to locate an item. To do this, you can use a starting point that determines the beginning of the first. Then, to locate an item, you can check whether another item follows that starting point. If no item follows it, either you are at the end of the list or the list is empty.

To be able to scan a list from one item to another, you can declare a field. Although this member variable can be called anything, for the sake of clarify, you should call it Next. The field is the same type as its class. Here is an example:

public class Number
{
    public double Item;
    public Number Next;
}

Practical LearningPractical Learning: Creating a List's Monitor

  1. Access the Flower.cs file and change it as follows:
     
    using System;
    
    namespace FlowerShop4
    {
        . . . No Change
    
        public sealed class Flower
        {
            . . . No Change
    
            public decimal UnitPrice
            {
                get { return pc; }
                set { pc = value; }
            }
    
            public Flower Next;
        }
    }
  2. Access the FlowerInventory.cs file and change it as follows:
     
    using System;
    
    namespace FlowerShop4
    {
        public abstract class AFlower
        {
            protected int items;
    
            public AFlower()
            {
                items = 0;
            }
    
            public int Count
            {
                get { return items; }
            }
        }
    
        public class FlowerInventory : AFlower
        {
            public Flower Head;
            public Flower Inventory;
    
            public FlowerInventory()
            {
                Head = null;
            }
        }
    }
  3. Save all
 

Previous Copyright © 2006-2007 FunctionX, Inc. Next