Collections in C#

As a programmer, it is a challenge to manage the data and group the data. It is necessary to store data or information in some ordered manner.

The .NET Framework’s System.Collections namespace provides several types of collections. These collections are pre-defined classes.

  • ArrayList
  • SortedList
  • Queue
  • Stack
  • Hashtable
  • BitArray
  • StringCollection
  • StringDictionary
  • ListDictionary
  • HybridDictionary
  • NameValueCollection
All the above given classes are used to manage the data. We have to understand how we can use these classes in different situation. Every collection class is important and unique. The key point is that we must know when and in which situation we should use these classes.

ArrayList

Array is very simple to use but the main drawback of array is:

  • You cannot add heterogeneous items in Array.
  • You have to provide size of the array at the time of its declaration.
  • In many cases, lot of memory is wasted in array.
Above problems are removed by ArrayList class. Its size is dynamically increased as required. We can add heterogeneous item in ArrayList. The ArrayList collection is a simple class. It uses Add () and AddRange () methods for adding items to the collection. The Add method allows you to add a single object and AddRange () method is used to add a range of items in collection.

Note: ArrayList is not type safe.

The Add and AddRange methods add items to the end of the collection. You can also add items at specific location by using Insert and InsertRange methods.

Example

using System;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList myList = new ArrayList();
            //Adding item type string
            myList.Add("One");
            myList.Add("Two");
            myList.Add("Three");
            //Adding item type integer
            myList.Add(100);
            myList.Add(200);
            Console.WriteLine("\n Items in the list \n");
            foreach (object item in myList)
            {
                Console.WriteLine(item);
            }
            // Using the insert method
            myList.Insert(4, "Four");
           
            Console.WriteLine("\n Items in the list after inserting new item in fourth place \n");
            foreach (object item in myList)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}


Execute the above program, you will find the following output.

Output:

Items in the list

One
Two
Three
100
200

Items in the list after inserting
new item in fourth place

One
Two
Three
100
Four
200


Let us understand the above program. ArrayList is a class that is available in System.Collections namespace. For accessing the member function of the ArrayList class, first create an object of the class. By using Add() method, you can insert heterogeneous items in this list. But with our traditional way of understanding, array is a collection of elements of similar or homogenous types, then certainly we come across one question “How it is possible to add heterogeneous items in the list by using Add() method?”

The answer is, Add() method is having Object as input parameter type and Object is most base class in the Dot Net. So whatever type of item you add in ArrayList, it will get converted into type Object automatically.

You can also access the individual item from list as given below.

string item = (string)myList[1];
Console.WriteLine(item);


When you add the item in the list and then access the item, Boxing and Unboxing done internally.

Example

using System;
using System.Collections;
namespace ConsoleApplication1
{   
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList myList = new ArrayList();
            Console.WriteLine("Initial status of List");
            Console.WriteLine("   Count    : {0}", myList.Count);
            Console.WriteLine("   Capacity : {0}", myList.Capacity);
            // Adding item type string
            myList.Add("One");

            Console.WriteLine("After adding one item in the list ");
            Console.WriteLine("   Count    : {0}", myList.Count);
            Console.WriteLine("   Capacity : {0}", myList.Capacity);
            myList.Add("Two");
            myList.Add("Three");
            // Adding item type integer
            myList.Add(100);           
            myList.Add(200);
            myList.Add(200);
            Console.WriteLine("After adding six item in the list ");
            Console.WriteLine("   Count    : {0}", myList.Count);
            Console.WriteLine("   Capacity : {0}", myList.Capacity);
            myList.TrimToSize();
            Console.WriteLine("Trim the list ");
            Console.WriteLine("   Count    : {0}", myList.Count);
            Console.WriteLine("   Capacity : {0}", myList.Capacity);
           
            Console.WriteLine("\n Items in the list \n");
            foreach (object item in myList)
            {
                Console.Write(item+"    ");
            }           
            Console.ReadLine();
        }
    }
}


Execute the above program, you will find the following output.

Output:

Initial status of List
   Count      : 0
   Capacity : 0
After adding one item in the list
   Count      : 1
   Capacity : 4
After adding six item in the list
   Count     : 6
   Capacity : 8
Trim the list
   Count     : 6
   Capacity : 6

Items in the list

One    Two    Three    100    200    200


Let’s understand the above program. Initially the list is empty that’s why the value of count and capacity is zero. When you add first element in the list, the count and capacity become one and four. Because ArrayList grows dynamically, so when you add first element, its capacity become four. When you add fifth element, its capacity become eight and so on.

TrimToSize() Method of ArrayList class sets the capacity to its actual number of element. It enables you to minimize the wastage of memory overhead.

Key things of ArrayList class

  • The ArrayList is a simple class and add items in unordered manner.
  • The ArrayList is used for heterogeneous collection of items.
  • It grows at dynamically ( at runtime).
  • The Add and AddRange methods of the ArrayList are used to add items to an ArrayList.
  • The Insert and InsertRange() methods of the ArrayList are used to insert items into specific places in a collection.
  • For deleting the item from ArrayList Remove (), RemoveAt(), and RemoveRange() methods are used.

Sequential Lists

The Stack and Queue classes are used to store data in a sequential basis.

Stack class

Stack class works as last-in, first-out (LIFO) manner.

Following are the important property and methods of Stack class.

Property
  • Count
Methods
  • Pop
  • Push
  • Peek

Example

using System;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack stackObj = new Stack();
            stackObj.Push("One");
            stackObj.Push("Two");
            stackObj.Push("Three");            
            Console.WriteLine("\tDisplays the properties and values of the Stack\n");
            Console.WriteLine("\tCount:    {0}", stackObj.Count);
            Console.Write("\tValues:");
           
            foreach (Object obj in stackObj)
            {
                Console.Write("    {0}", obj);
            }
            Console.WriteLine("\n\n");
            Console.Write("\tPopped Values from stack:\n");
            while(stackObj.Count>0)
            {
                Console.Write("\t{0}", stackObj.Pop());
            }           
            Console.ReadLine();
        }
    }
}


Output:
        Displays the properties and values of the Stack
        Count:    3
        Values:    Three    Two    One
        Popped Values from stack:
        Three   Two     One

You will not get any item in stack after popped from stack.

Peek () method is used to retrieves the top item from the stack without removing it.

Queue class

Queue is another straightforward class. First create the object of the class and use the Enqueue method to add items to the queue and the Dequeue method to remove items.

Following are the important property and methods of Queue class.

Property
  • Count
Methods
  • Dequeue
  • Enqueue
  • Peek

Example

using System;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue myQueue = new Queue();
            myQueue.Enqueue("One");
            myQueue.Enqueue("Two");
            myQueue.Enqueue("Three");
            myQueue.Enqueue("Four");
            Console.WriteLine("\tDisplays the queue item\n");
            while (myQueue.Count > 0)
            {
                object obj = myQueue.Dequeue();
                Console.WriteLine("\t{0}", obj);
            }
             Console.ReadLine();
        }
    }
}


Key things of Queue class:

  • A queue works on FIFO principle, first in first out data structure.
  • A queue can hold any object.
  • Enqueue() method is used to add items in the queue.
  • Dequeue() method is used to remove items from the queue.
  • You can get the number of items in the queue using the count () method.