Using .NET Collections With C#

Objective of the Module

  • Introduction
  • ArrayList
  • Hashtable
  • BitArray

Introduction

.NET offers a variety of collections, such as ArrayList, Hashtable, queues, Dictionaries. Collections are abstractions of data algorithms. An ArrayList is an abstract dynamic array, a Hashtable collection abstracts a lookup table, a Queues collection abstracts queues and so on. In addition to that, collections implement the ICollection, IEnumerable and IClonable interfaces. The detailed specification for each collection is found under the System.Collection namespace.

ArrayList Collection

An ArrayList is a dynamic array and implements the IList interface. Each element is accessible using the indexing operator. While the traditional array has a fixed number of elements, in the case of Array List, elements can be added or removed at run time.

We can create an object of ArrayList using a general type of syntax as follows;

ArrayList obj = new ArrayList();

Here you can use the new keyword to create an instance of the ArrayList object. You don't need to specify the size. Once you have an empty ArrayList object, you can use the Add() method to add elements to it,as in:

obj.Add("item1");
obj.Add("2");
obj.Add("Delhi");

Each new item in the ArrayList is added to the end of the list, so it has the largest index number. If you wanted to add an item in the middle of the list, then you can use "Insert()" with a numeric argument as follows:

Obj.Insert(2,"item2");

You can also remove members of the ArrayList using either Remove() or RemoveAt() methods as in the following:

Obj.Remove("item1");
Obj.RemoveAt(3);

Benefits of ArrayLists

  • Insert Elements: An ArrayList starts with a collection containing no elements. You can add them in any position as you choose them.
  • Automatic Resizing: you do not need to specify the array size; as you add elements, the array automatically ensures there is enough memory for the array.
  • Flexibility When Removing Elements: you can remove any element from an Arraylist very easily.

Limitations of ArrayLists

The flexibility of ArrayList comes at a cost of performance. Since memory allocation is a very expensive business, the fixed number of elements of the simple array makes it much faster to work with.

Note: ArrayLists are slower and more resource-intensive than a conventional array.

Simple ArrayList Example

The following example shows an array list with an #ff0000 size. Elements are added dynamically as required. We are adding elements using the "Add()" method as well as using the "Insert()" method at a specific location. Later we are displaying all the elements by iterating through the list.

using System;
using System.Collections;

namespace CollectionApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //Defining an ArrayList
            ArrayList obj = new ArrayList();

            //Adding elements
            obj.Add("India");
            obj.Add("USA");
            obj.Add("Russia");
            obj.Add("300");

            //Adding elements to specific position
            obj.Insert(2, "Japan");

            //Accessing elements
            for (int i = 0; i < obj.Count;i++ )
            {
                Console.WriteLine("At Index["+i+"]= "+obj[i].ToString());
            }

            Console.WriteLine("____________");
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
    }
}


After building and running this program, the output of the program is as in the following;

Array-List.jpg

Figure 1.1 - Array List

Hashtables

In some respects, Hashtable objects are quite similar to an ArrayList object except that it is not required to use a numerical index. Instead, we can use a texture key that can be numeric.

You can create a Hashtable object by using the same syntax as an ArrayList as in the following:

Hashtable obj = new Hashtable();

Once it is created, you must specify the key/value pairs. Remember that the key is like an index for the entry and the value is the data we are storing. We store each element using the "Add()" method with the following syntax;

Obj["in"] = "india";
Obj["en"] = "England";
Obj["us"] = "USA";

A Hashtable with numbers or dates for the keys are written as in the following;

Obj[Convert.ToDateTime("21/12/2012")] = "The Judgment day";

Note: you need to convert DateTime index values when they are used as an index for a Hashtable.

To read elements, you just need to specify the key and the value is returned. The following code puts the value "india" into a variable named Country:

string Country = Convert.ToString(obj["in"]);

Benefits of Hashtable

  • Insert Elements: you can add as many pairs of key/value elements as required. You do not have to specify the size ahead of time.
  • Non-numeric index: you can use text, number and dates as your key (index).
  • Faster Lookup: the hashtable collection caters very fast lookup of elements.
  • Flexibility when Removing elements: you can remove any element from an Arraylist very easily

Limitations of Hashtable

  • Key must be unique: The Hashtable stipulates the key uniqueness requirement that is very cumbersome to manipulate.
  • No useful sorting: Sorting is not done by using keys or values. The items in the Hashtable are sorted internally to make it easy to find objects very quickly.
  • Performance: Although the lookup is very quick in a Hashtable, the CLR must do quite a lot of work to maintain them that is very resource-intensive.

Simple Hashtable Example

The following Hashtable program uses a date index. First we define a Hashtable object and add some predefined dates. Thereafter we create a DateTime type variable to store user input and finally we display the output.

using System;
using System.Collections;

namespace CollectionApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //Defining an Hashtable
            Hashtable obj = new Hashtable();

            //Adding elements
            obj[Convert.ToDateTime("02/14/2012")] = "Valentine day";
            obj[Convert.ToDateTime("12/22/2012")] = "Math day";
            obj[Convert.ToDateTime("08/15/1947")] = "Independence day";
 
            //input date from user
            Console.WriteLine("Enter date 'Month/Date/Year' Format");
            DateTime DateData = DateTime.Parse(Console.ReadLine());
           
            //display data
            Console.WriteLine(obj[DateData]);
           
            Console.WriteLine("____________");
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
    }
}


After successfully compiling the aforementioned program, the output is as in the following;

Hashtable.jpg

Figure 1.2 - Hashtable

BitArray

Bit values are ones and zeros, where 1 represents true and 0 is false. A BitArray collection provides an efficient means of storing and retrieving bit values. It allows us to perform bitwise operations as well as count the total number of bits. The contents of this collection are not Objects but Boolean values because a BitArray can hold a large number of Boolean values which are called bits. One of most significant features of a BitArray is resizability, that is useful if you don't know the number of bits needed in advance.

You can create a BitArray object by using the same syntax as defined for other collections. BitArray provides several constructors. We are defining 7 bits in length in the BitArray in the following:

BitArray obj = new BitArray(7);

Note: The static members of BitArray are threaded-safe whereas instance members are not.

Simple BitArray Example

The following program demonstrates BitArray manipulation. It creates a bit array with 16 bits, indexed from 0 to 15. The Count Property calculates the total number of bits. The SetAll() method sets all the 16 bits to true. Then the Set() method changes the third bit to false. Instead of the Set method, you can also use an indexer.

using System;
using System.Collections;

namespace CollectionApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // BitArray definition
            BitArray bobj = new BitArray(16);

            // calaculate total bits
            Console.WriteLine("Total bits="+bobj.Count);
            //set all bits to 1
            bobj.SetAll(true);

            //set 2nd bit to false
            bobj.Set(2, false);

            //set bit using Indexer
            bobj[3] = false;

            DislayBits(bobj);

            Console.WriteLine("\n___________");
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }

        static void DislayBits(BitArray obj)
        {
            foreach(bool bits in obj)
            {
                if (bits)
                    Console.Write(1);  // Console.Write(bit ? 1 : 0);
                else
                    Console.Write(0);
            }
        }

    }
}

The displayed results of the initialized and configured bits are as in the following;

Bit-Array.jpg

Figure 1.3 - Bit Array

The BitArray collection implements the properties and methods of the ICollection interface. The following table shows the properties and methods of BitArray;

PropertiesMembersDescription
CountContains the number of items currently in the bitarray
IsReadOnlyContains True if the bitarray is read-only and False otherwise
IsSynchronizedContains True if the bitarray is synchronized and False otherwise
Item[]Contains an index of all the items in the bitarray
LengthEnables the developer to get and change the length of the bitarray
MethodsAnd()Performs the logical "And" operation on the bitarray
Clone()Returns a copy of the bitarray
CopyTo()Copies the bitarray to another type of collection
Get()                Returns the value of a specific location in the bitarray
Not()Performs the logical "Not" operation on the bitarray
Or()Performs the logical "Or" operation on the bitarray
Set()Sets the value of a specific location in the bitarray
SetAll()Sets all the values in the bitarray