Overview of Collections in .NET

Objective of the Module

  • Introduction
  • ArrayList
  • Hashtable
  • BitArray

Introduction

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

ArraysList Collection

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

We can an object from the ArrayList using a general type of syntax as follows:

  1. 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 the following:

  1. obj.Add(“item1”);  
  2. obj.Add(“2”);  
  3. 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 to the middle of the list, then you can use Insert() with a numeric argument as follows:

  1. Obj.Insert(2,“item2”); 

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

  1. Obj.Remove(“item1”);  
  2. 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 of the array.

  • Flexibility when Removing elements: you can remove any elements from an Arraylist very easily.

Limitations of ArrayLists

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

Note: an ArrayList is slower and more resource-intensive than a conventional array.

Simple ArrayList Example

The following example shows an array list with an undefined size. Elements are adding dynamically depending on the requirements. We are adding elements via the Add() method as well as using the Insert() method at a specific location. Later we are displaying all the elements by iterating using a for loop.

  1. using System;  
  2. using System.Collections;  
  3.   
  4. namespace CollectionApp  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             //Defining an ArrayList  
  11.             ArrayList obj = new ArrayList();  
  12.   
  13.             //Adding elements  
  14.             obj.Add("India");  
  15.             obj.Add("USA");  
  16.             obj.Add("Russia");  
  17.             obj.Add("300");  
  18.   
  19.             //Adding elements to specific position  
  20.             obj.Insert(2, "Japan");  
  21.   
  22.             //Accessing elements  
  23.             for (int i = 0; i < obj.Count;i++ )  
  24.             {  
  25.                 Console.WriteLine("At Index["+i+"]= "+obj[i].ToString());  
  26.             }  
  27.   
  28.             Console.WriteLine("_________________");  
  29.             Console.WriteLine("Press any key");  
  30.             Console.ReadKey();  
  31.         }  
  32.     }  

After build-up and the running of this program, the output of the following program is as in the following:

Array List
                                       Figure 1.1 – Array List

Hashtables

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

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

  1. Hashtable obj = new Hashtable(); 

Once it is created, you need to 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 elements using the Add() method with the following syntax as in the following:

  1. Obj[“in”] = “india”;  
  2. Obj[“en”] = “England”;  
  3. Obj[“us”] = “USA”; 

A Hash table with numbers or dates for the keys are written as in the following:

  1. 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 value is returned. The following code puts the value “india” into a variable named Country.

  1. 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 need 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 elements from an Arraylist very easily.

Limitations of ArrayLists

  • Key must be unique: Hashtables have a key uniqueness requirement that is very cumbersome to manipulate.

  • No useful sorting: Sorting is not done using keys or values. Items in a 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 much work to keep its mechanism that is very resource-intensive.

Simple Hashtable Example

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

  1. using System;  
  2. using System.Collections;  
  3.   
  4. namespace CollectionApp  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             //Defining an Hashtable  
  11.             Hashtable obj = new Hashtable();  
  12.   
  13.             //Adding elements  
  14.             obj[Convert.ToDateTime("02/14/2012")] = "Valentine day";  
  15.             obj[Convert.ToDateTime("12/22/2012")] = "Math day";  
  16.             obj[Convert.ToDateTime("08/15/1947")] = "Independence day";  
  17.   
  18.             //input date from user  
  19.             Console.WriteLine("Enter date 'Month/Date/Year' Format");  
  20.             DateTime DateData = DateTime.Parse(Console.ReadLine());  
  21.               
  22.             //display data  
  23.             Console.WriteLine(obj[DateData]);  
  24.               
  25.             Console.WriteLine("_________________");  
  26.             Console.WriteLine("Press any key");  
  27.             Console.ReadKey();  
  28.         }  
  29.     }  

After successfully compiling the program mentioned previously, the output is as in the following:

Hashtable
                                      Figure 1.2: Hashtable

BitArray

Bit values are 1 and 0, where 1 represents true and 0 is false. A BitArray collection provides an efficient way to store and retrieve 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 BitArray can hold a large number of Boolean values called bits. One of most significant features of a BitArray is that they are resizable and that is useful if you don't know the number of bits needed in advance.

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

  1. BitArray obj = new BitArray(7); 

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

Simple BitArray Example

The following program shows 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.

  1. using System;  
  2. using System.Collections;  
  3.   
  4. namespace CollectionApp  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             // BitArray definition  
  11.             BitArray bobj = new BitArray(16);  
  12.   
  13.             // calaculate total bits  
  14.             Console.WriteLine("Total bits="+bobj.Count);  
  15.             //set all bits to 1  
  16.             bobj.SetAll(true);  
  17.   
  18.             //set 2nd bit to false  
  19.             bobj.Set(2, false);  
  20.   
  21.             //set bit using Indexer  
  22.             bobj[3] = false;  
  23.   
  24.             DislayBits(bobj);   
  25.               
  26.             Console.WriteLine("\n_________________");  
  27.             Console.WriteLine("Press any key");  
  28.             Console.ReadKey();  
  29.         }  
  30.   
  31.         static void DislayBits(BitArray obj)  
  32.         {  
  33.             foreach(bool bits in obj)  
  34.             {  
  35.                 if (bits)  
  36.                     Console.Write(1);  // Console.Write(bit ? 1 : 0);  
  37.                 else  
  38.                     Console.Write(0);  
  39.             }  
  40.         }  
  41.           
  42.     }  

The following is a display of the results of the initialized and configured bits:

Bit Array
                                       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:

  Members Descriptions
Properties Count Contains the number of items currently in the bitarray
IsReadOnly Contains True if the bitarray is read-only and False otherwise
IsSynchronized Contains True if the bitarray is synchronized and False otherwise
Item[] Contains an index of all the items in the bitarray
Length Enables the developer to get and change the length of the bitarray
Methods And() 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


Similar Articles