Fundamentals of Collections

Introduction

A collection, also called a list, is a group of items. Normally, the items should be of the same type. The collection can be made of numbers, or symbols, or dates, or strings, etc. The collection can also be made of objects (of a class), such as houses, people, cars, countries, etc. The primary rule to observe is that all items included in a list must be described using the same characteristics.

Starting a Collection

To start a collection, create a class. This class would be used to add items in the collection, to remove items in the list, or to perform other necessary operations. You can start a simple class as follows:

public class Collection
{
}

Since this is a normal class, you can add various types of members to it, including properties, methods, etc. Here is an example of a class with a constructor:

public class State
{
    public Collection()
    {
    }
}

After creating the class for a collection, the collection becomes an object and its class can be used like any other. This means that, before using the collection, you can declare a variable for it. Here are examples of such variables:

<!DOCTYPE html>
<html>
<head>
<title>States Statistics</title>
</head>
<body>
<h3>States Statistics</h3>

@{
    Collection states = new Collection();
    var estados = new Collection();
    dynamic pays = new Collection();
}

</body>
</html>

As we saw in previous lessons, an array is one type of list you can create. In fact, to create a collection, you can start by adding a field array as one of its members. Here is an example:

public class Collection
{
    private string[] items;

    public Collection()
    {
        items = new string[10];
    }
}

There are many other ways you can start an array.

The Number of Items in a Collection

It is important to know the number of items in a collection at any item. If you create a collection that is array-based, because you must specify the number of items that the array will contain, you would the number of items. To keep track of the number of items in the collection, you create a private field and initialize it to 0 in the constructor to indicate its primary number of items. Here is an example:

public class Collection
{
    // This is the size of the collection
    private int size;
    private string[] items;

    public Collection()
    {
        size = 0;
        items = new string[10];
    }
}

Since the size field was declared private, if you plan to get the count of items in the list from outside the class, you should (must) provide a property to take care of this. This can simply be done as follows:

public class Collection
{
    // This is the size of the collection
    private int size;
    private string[] items;

    public Collection()
    {
        size = 0;
        items = new string[10];
    }

    // This represents the number of items in the collection
    public int Count
    {
        get { return size; }
    }
}

Here is an example of accessing the number of items in the collection:

<!DOCTYPE html>
<html>
<head>
<title>States Statistics</title>
</head>
<body>
<h3>States Statistics</h3>

@{
    Collection states = new Collection();
}

<p>The list contains @states.Count items</p>
</body>
</html>

This would produce:

Introduction to Collections

Routine Operations on an Array-Based List

Adding a Value to a Collection

The primary operation performed on a collection consists of adding an items to it, and then adding other items. The easiest way to do this is to add an item at the end of the existing collection.

To add an item to the collection, because an array has (or is supposed to have) a fixed number of items, you should first check whether the list is already full. For an array-based list, the collection is full if its count of items is equal to the maximum number of items it can hold. If the collection can still receive at least one item, you can add the item at the end of the list and increase the count by one. Here is how this can be done:

public class Collection
{
    // This is the size of the collection
    private int size;
    private string[] items;

    #region This section is used to set up the collection
    public Collection()
    {
        size = 0;
        items = new string[10];
    }

    // This represents the number of items in the collection
    public int Count
    {
        get { return size; }
    }
    #endregion

    #region Operations on the collection
    // Adds a new item to the list if the list is not full
    // Increases the number of items in the list
    // Returns true if the item was added, otherwise returns false
    public bool Add(string item)
    {
        // Make sure the list is not yet full
        if (this.size < 10)
        {
            // Since the list is not full, add the item at the end
            this.items[this.size] = item;
            // Increase the count and return the new position
            this.size++;

            // Indicate that the item was successfully added
            return true;
        }

        // If the item was not added, return false;
        return false;
    }
    #endregion
}

Once you have a means of adding items to the list, you can effectively create a list of items. Here is an example:

@{
    Collection Brazil = new Collection();

    Brazil.Add("Pernambuco");
    Brazil.Add("Maranhão");
    Brazil.Add("Acre");
    Brazil.Add("Ceará");
}

Getting an Item From a Collection

After adding items to a collection, you can retrieve them, for any reason. To retrieve an item, you can locate it by its position, especially if you had created/started the collection from an array. Having this index, you can check whether the position specified is negative or higher than the current count of items. If it is, there is nothing much to do since the index would be wrong. If the index is in the right range, you can retrieve its corresponding item. The method to do this can be implemented as follows:

public class Collection
{
    . . . No Change

    #region Operations on the collection

    . . . No Change

    // This method retrieves an item from the list based on the specified index
    public string Get(int pos)
    {
        // Make sure the index is in the range
        if (pos >= 0 && pos <= size)
            return items[pos];

        // If the index was wrong, return 0
        return string.Empty;
    }
    #endregion
}

Here is an example of calling the method repeatedly in a loop:

<!DOCTYPE html>
<html>
<head>
<title>States Statistics</title>
</head>
<body>
<h3>States Statistics</h3>

@{
    Collection Brazil = new Collection();

    Brazil.Add("Pernambuco");
    Brazil.Add("Maranhão");
    Brazil.Add("Acre");
    Brazil.Add("Ceará");
    Brazil.Add("Rio Grande do Norte");
    Brazil.Add("São Paulo");
    Brazil.Add("Goiás");
    Brazil.Add("Mato Grosso");
    Brazil.Add("Santa Catarina");
    Brazil.Add("Pernambuco");
}

<p>The list contains @Brazil.Count items</p>
<ul>
@for (int i = 0; i < Brazil.Count; i++)
{
    <li>@Brazil.Get(i)</li>
}
</ul>
</body>
</html>

Inserting an Item in the List

Inserting a new item in the collection allows you to add one at a position of your choice. To insert an item in the list, you must provide the new item and the desired position. Before performing this operation, you must check two things. First, the list must not be empty because if it is, then there is no way to insert an item (you insert something between two things, not something between nothing). Second, the specified position must be in the allowed range. Here is an example of performing this operation:

public class Collection
{
    . . . No Change

    // Before performing this operation, check that
    // 1. The list is not full
    // 2. The specified position is in an allowable range
    // Insert a new item at a specified position in the list.
    // After the new item is inserted, the count is increased
    public bool Insert(string itm, int pos)
    {
        // Check that the item can be added to the list
        if (size < Count && pos >= 0 && pos <= size)
        {
            // Since there is room,
            // starting from the end of the list to the new position,
            // push each item to the next or up
            // to create room for the new item
            for (int i = size; i > pos - 1; i--)
                items[i + 1] = items[i];

            // Now that we have room, put the new item in the position created
            items[pos] = itm;

            // Since we have added a new item, increase the count
            size++;

            // Indicate that the operation was successful
            return true;
        }

        // Since the item could not be added, return false
        return false;
    }
    #endregion
}

Here is an example of calling the method:

<!DOCTYPE html>
<html>
<head>
<title>States Statistics</title>
</head>
<body>
<h3>States Statistics</h3>

@{
    Collection Brazil = new Collection();

    Brazil.Add("Pernambuco");
    Brazil.Add("Maranhão");
    Brazil.Add("Acre");
    Brazil.Add("Ceará");
    Brazil.Add("Rio Grande do Norte");
    Brazil.Add("São Paulo");
    Brazil.Add("Goiás");
    Brazil.Add("Mato Grosso");
    Brazil.Add("Santa Catarina");
    Brazil.Add("Pernambuco");

    Brazil.Insert("Espírito Santo", 5);
}

<p>The list contains @Brazil.Count items</p>
<ul>
@for (int i = 0; i < Brazil.Count; i++)
{
    <li>@Brazil.Get(i)</li>
}

</ul>
</body>
</html>

Removing an Item From a Collection

Another operation you can perform on a collection consists of deleting an item. This is also referred to as removing the item. To delete an item from a collection, you can provide its position. Before performing the operation, you can (should/must) first check that the specified position is valid. The method to perform this operation can be implemented as follows:

public class Collection
{
    // This is the size of the collection
    private int size;
    private string[] items;

    #region This section is used to set up the collection
    public Collection()
    {
        size = 0;
        items = new string[10];
    }

    // This represents the number of items in the collection
    public int Count
    {
        get { return size; }
    }
    #endregion

    #region Operations on the collection
    // Adds a new item to the list if the list is not full
    // Increases the number of items in the list
    // Returns true if the item was added, otherwise returns false
    public bool Add(string item)
    {
        // Make sure the list is not yet full
        if (size < 10)
        {
            // Since the list is not full, add the item at the end
            items[size] = item;
            // Increase the count and return the new position
            size++;

            // Indicate that the item was successfully added
            return true;
        }

        // If the item was not added, return false;
        return false;
    }

    // This method retrieves an item from the list based on the specified index
    public string Get(int pos)
    {
        // Make sure the index is in the range
        if (pos >= 0 && pos <= size)
            return items[pos];

        // If the index was wrong, return 0
        return string.Empty;
    }

    // Before performing this operation, check that
    // 1. The list is not full
    // 2. The specified position is in an allowable range
    // Insert a new item at a specified position in the list.
    // After the new item is inserted, the count is increased
    public bool Insert(string itm, int pos)
    {
        // Check that the item can be added to the list
        if (size < Count && pos >= 0 && pos <= size)
        {
            // Since there is room,
            // starting from the end of the list to the new position,
            // push each item to the next or up
            // to create room for the new item
            for (int i = size; i > pos - 1; i--)
                items[i + 1] = items[i];

            // Now that we have room, put the new item in the position created
            items[pos] = itm;

            // Since we have added a new item, increase the count
            size++;

            // Indicate that the operation was successful
            return true;
        }

        // Since the item could not be added, return false
        return false;
    }

    // This method removes an item from the list
    // First check that the specified position is valid
    //-- Delete the item at that position and decrease the count --//
    public bool Delete(int pos)
    {
        // Make sure the position specified is in the range
        if (pos >= 0 && pos <= size)
        {
            // Since there is room, starting at the specified position,
            // Replace each item by the next
            for (int i = pos; i < size; i++)
                items[i - 1] = items[i];

            // Since an item has been removed, decrease the count
            size--;

            // Indicate that the operation was successful
            return true;
        }

        // Since the position was out of range, return false
        return false;
    }
    #endregion
}

Here is an example of calling the method:

<!DOCTYPE html>
<html>
<head>
<title>States Statistics</title>
</head>
<body>
<h3>States Statistics</h3>

@{
    Collection Brazil = new Collection();

    Brazil.Add("Pernambuco");
    Brazil.Add("Maranhão");
    Brazil.Add("Acre");
    Brazil.Add("Ceará");
    Brazil.Add("Peyton");
    Brazil.Add("Rio Grande do Norte");
    Brazil.Add("São Paulo");
    Brazil.Add("Goiás");
    Brazil.Add("Mato Grosso");
    Brazil.Add("Santa Catarina");
    Brazil.Add("Pernambuco");

    Brazil.Insert("Espírito Santo", 5);
}

<h4>-- States --</h4>
<ul>
    @for (int i = 0; i < Brazil.Count; i++)
    {
        <li>@Brazil.Get(i)</li>
    }
</ul>

@{
    Brazil.Delete(5);
}

<h4>-- States --</h4>
<ul>
    @for (int i = 0; i < Brazil.Count; i++)
    {
        <li>@Brazil.Get(i)</li>
    }
</ul>
</body>
</html>

This would produce:

Removing an Item From a Collection

A Collection of Items

Introduction

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 and specify in advance the number of items that will make up the list. There are times when you don'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.

Starting 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 create a field of the desired type. Here is an example:

public class Collection
{

}

Here is an example of declaring a variable of this clas:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    Collection storeItems = new Collection();
}

</body>
</html>

The Type of the Items of a Collection

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:

public class Item
{
    public string Value;
}

public class Collection
{
    private Item Sample;
}

Here is an example of specifying a value of an item of a collection:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    Collection storeItems = new Collection();

    Item itm = new Item();
    itm.Value = "Floral Blouson Midi Dress";
}

</body>
</html>

When creating a list, you should 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 when an item is removed from the list. Here is how this can be done:

public class Item
{
    public string Value;
}

public class Collection
{
    int size;

    public Collection()
    {
        size = 0;
    }

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

Here is an example of getting the number of items of a collection:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    Collection storeItems = new Collection();

    Item itm = new Item();
    itm.Value = "Floral Blouson Midi Dress";
}

<p>Number of Items: @storeItems.Count</p>
</body>
</html>

This would produce:

Removing an Item From a Collection

The Beginning of a Collection

A typical collection grows or shrinks regularly. 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. To specify this, you should declare a primary member variable. Although you can call it anything, it is usually called Head:

Collection

The head member can be made private if you don't intend to access it outside the class. If you want clients of the class to access it, you can make it public. Here is an example:

public class Item
{
    public string Value;
}

public class Collection
{
    int size;

    public Item Head;

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

    public int Count => size;
}

Linking the Items of a Collection

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 list. Then, to locate an item, you can check whether another item follows that starting point:

Collection

If no item follows an item, 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 clarity, you should call it Next. The field is the same type as its class. Here is an example:

public class Item
{
    public string Value;
    public Item Next;
}

Operations on a Collection

Adding an Item

Since a list is fundamentally empty when it starts, the primary operation you can perform on a list is to add a new item to it. In order to indicate that you want to add an item to the list, you can create a method that receives an item as argument. For the return type, you have two main options. Because the main job of this method is to add a new item, which it hardly fails to do if you implement it right, it can be defined as void. Alternatively, you can make it return the position of the new item in the list. Here is an example:

public class Item
{
    public string Value;
    public Item Next;
}

public class Collection
{
    int size;
    public Item Head;

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

    public int Count
    {
        get { return size; }
    }

    public int Add(Item nItem)
    {
        Item sample = nItem;
        sample.Next = this.Head;
        this.Head = sample;

        return size++;
    }
}

Here are examples of calling this method:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    Collection storeItems = new Collection();

    Item itm = new Item();
    itm.Value = "Floral Blouson Midi Dress";

    storeItems.Add(itm);
    itm = new Item();
    itm.Value = "Heathered Sweatpants";
    storeItems.Add(itm);
    itm = new Item();
    itm.Value = "Bellow Leather Knee-High Boots";
    storeItems.Add(itm);
}

<p>Number of Items: @storeItems.Count</p>
</body>
</html>

This would produce:

Removing an Item From a Collection

Getting an Item from a Collection

To locate and retrieve an item of a collection, you can create a method that takes an index as argument. The method would examine the argument with regards to the number of items in the list to make sure the argument's value is in the range of the current items of the list. If the number is too low or too high, the method can return null, 0, or throw an exception. If the number is in the range, the method can return the item at that position. Here is an example:

. . . No Change

    public Item Get(int index)
    {
        Item current = this.Head;

        for (int i = this.size - 1; i > index && current != null; i--)
            current = current.Next;

        return current;
    }
}

Here is an example of getting the items of a collection:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    Collection storeItems = new Collection();

    Item itm = new Item();
    itm.Value = "Floral Blouson Midi Dress";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Heathered Sweatpants";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Bellow Leather Knee-High Boots";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Pleated A-Line Skirt";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Long Sleeve Blouse";
    storeItems.Add(itm);
}

<ul>
    @for (int i = 0; i < @storeItems.Count; i++)
    {
        <li>@storeItems.Get(i).Value</li>
    }
</ul>
</body>
</html>

This would produce:

Getting an Item from a Collection

Removing an Item

Deleting an item consists of removing it from the collection. There are various issues involved and varous ways this can be done. One way is to remove the first item (the head) of the collection. Always make sure you perform other routine operations such as decrementing the count of items in the list. Here is an example of how this can be done:

public class Collection
{
    . . . No Change

    public bool Delete()
    {
        if (Head == null)
        {
            // The list is empty
            return false;
        }

        Item Current;

        Current = Head.Next;
        Head.Next = Current.Next;
        size--;
        return true;
    }
}

Here is an example of calling this method:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    Collection storeItems = new Collection();

    Item itm = new Item();
    itm.Value = "Floral Blouson Midi Dress";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Heathered Sweatpants";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Bellow Leather Knee-High Boots";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Pleated A-Line Skirt";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Long Sleeve Blouse";
    storeItems.Add(itm);
}

<ul>
    @for (int i = 0; i < @storeItems.Count; i++)
    {
        <li>@storeItems.Get(i).Value</li>
    }
</ul>

@{ 
    storeItems.Delete();
}

<ul>
    @for (int i = 0; i < @storeItems.Count; i++)
    {
        <li>@storeItems.Get(i).Value</li>
    }
</ul>

</body>
</html>

This would produce:

Getting an Item from a Collection

Another technique used to delete an item is to specify the position of the item to be deleted. To do this, you can pass an argument as the desired position. The method would check the range of values of the current list. If the specified position is beyond the appropriate range, the method can return false, 0, or null, depending on how you create it.

Checking Whether a Collection Contains an Item

One of the operations usually performed on a list is to find out whether a list contains a certain item. One way you can do this is to completely define an item and pass it to the list. Only if the (exact) item is found in the list would it be recognized. Here is an example:

public class Item
{
    public string Value;
    public Item Next;
}

public class Collection
{
    int size;
    public Item Head;

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

    public int Count => size;

    public int Add(Item nItem)
    {
        Item sample = nItem;
        sample.Next = Head;
        Head = sample;

        return size++;
    }

    public Item Get(int index)
    {
        Item current = this.Head;

        for (int i = this.size - 1; i > index && current != null; i--)
            current = current.Next;

        return current;
    }

    public bool Delete()
    {
        if (Head == null)
        {
            return false;
        }

        Item current = Head.Next;
        Head.Next = current;
        size--;
        return true;
    }

    public bool Contains(Item obj)
    {
        Item current = new Item();

        if (obj == null)
            return false;

        for(current = Head; current != null; current = current.Next)
        {
            if (current.Value == obj.Value)
                return true;
        }
                    
        return false;
    }
}

Here are examples of calling this method:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    Collection storeItems = new Collection();

    Item itm = new Item();
    itm.Value = "Floral Blouson Midi Dress";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Heathered Sweatpants";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Bellow Leather Knee-High Boots";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Pleated A-Line Skirt";
    storeItems.Add(itm);

    itm = new Item();
    itm.Value = "Long Sleeve Blouse";
    storeItems.Add(itm);
}

<ul>
    @for (int i = 0; i < @storeItems.Count; i++)
    {
        <li>@storeItems.Get(i).Value</li>
    }
</ul>

@{ 
    Item dress = new Item();
    dress.Value = "Floral Blouson Midi Dress";

    bool found = storeItems.Contains(dress);
}

<p>The store contains @dress.Value: @found</p>

@{
    dress = new Item();
    dress.Value = "Floral Blouson Dress";

    found = storeItems.Contains(dress);
}

<p>The store contains @dress.Value: @found</p>
</body>
</html>

This would produce:

Getting an Item from a Collection


Home Copyright © 2008-2019, FunctionX Next