Jitesh Byahut 10/12/2014 3414

Collections in C#

Collection classes provide great flexibility in storing data in C#. Before Collections, for this purpose we use array, but array have some limitations like, array specify its size at the time of declaration, array only store items of same data type. For overcome these situation we use collections classes. Collections are more flexible than array in C#.

Use namespace System.Collections

Types of Collections:


1. ArrayList

2. Stack

3. Queue

4. Hashtable

5. SortedList

ArrayList

ArrayList can store elements of any data type. Like array, we don't need to specify the size of ArrayList at the time of it declaration. ArrayList collection class provide you to dynamically add or remove items from array. You can use ArrayList instead of array when you don't know the how many items will inserted. ArrayList is more used when all items are different data type.

MethodDescriptions
Add(object obj)For add an item(at the end) in the ArrayList.
Insert(int index, object obj)For add an item at specific index in the ArrayList.
Remove(object obj)For remove an item from the ArrayList.
RemoveAt(int index)For remove an item at specific index from the ArrayList.
Reverse()For reverse the order of items in the ArrayList.
Clear()For eempty or removing all items from ArrayList.

        // ArrayList Declaration

         ArrayList arraylist = new ArrayList();

 

        // Adding different data type in arraylist

 

        arraylist.Add("Asphelps");     // Adding string type

        arraylist.Add('A');            // Adding Char type

        arraylist.Add(12);              // Adding int type

        arraylist.Add(12.34);          // Adding double type

        arraylist.Add(DateTime.Now);   // Adding DateTime type

 

        // Retreiving items from ArrayList     

        foreach (var item in arraylist)

        {

            Response.Write(item);

            Response.Write("<br/>");

        }     

        // Output

 

        // Asphelps

        // A

        // 12

        // 12.34

        // 29-03-2014 11:52:06

 

        // Reverse the index of items in arraylist

        arraylist.Reverse();

 

        foreach (var item in arraylist)

        {

            Response.Write(item);

            Response.Write("<br/>");

        }

        // Output

 

        //29-03-2014 12:13:18

        //12.34

        //12

        //A

        //Asphelps

 

        // Remove an item from arraylist

        arraylist.Remove(12); 

                   // remove item which has integer value 12  i.e. third item form the arraylist

 

        // Remove a specific index item from arraylist

        arraylist.RemoveAt(0); // remove item which is at 0 index position i.e "Asphelps"

 

        // Insert an item at specific index in arraylist

        arraylist.Insert(0, "Asp-Helps"); 

                   // Insert an item at index 0 i.e. first position in the arraylist

 

 

        // Remove all items from arraylist

        arraylist.Clear(); // Clear the arraylist

 

        // You can Sort the arraylist, if it stored all items of same

        // data type, otherwise it will throw exceptions

        //list.Sort();

Stack

Stack is a kind of collection that can useful when you need to store data in a specific order for sequential processing. A Stack works on principle of LIFO - Last In First Out, which means that last item inserted into the stack will be the first item to be removed from stack.

The adding of an item into stack is known as Push operation, removing an item from stack is known as Pop operation and if an item only read from top of stack is known as Peek operation.

MethodDescriptions
Push(object obj)For add an item in the Stack.
Pop()For remove an item from the Stack.
Peek()For retrieving an item without removing from the Stack.
Clear()For empty or removing all items from the Stack.

        // Stack Declaration

        Stack stack = new Stack();

 

        // Add an item in stack

        stack.Push("Asphelps");

 

        // Count total number of items in stack

        int total = stack.Count;

 

        // Retrieving top item form stack without removing it.

        stack.Peek();

 

        // Remove item from stack

        stack.Pop();

 

        // Clear the stack

        stack.Clear();

 

        // Adding different data type items in stack

 

        stack.Push("Asphelps");     // Adding string type

        stack.Push('A');            // Adding Char type

        stack.Push(12);             // Adding int type

        stack.Push(12.34);          // Adding double type

        stack.Push(DateTime.Now);   // Adding DateTime type

 

        // Retrieving items from stack as LIFO

        // Pop() method not only return the item, but also remove the item from the stack

        while (stack.Count != 0)

        {

            Response.Write(stack.Pop());

            Response.Write("<br/>");

        }     

        // Output

 

        //29-03-2014 14:34:29

        //12.34

        //12

        //A

        //Asphelps

Queue

Similar to Stack, Queue can useful when you need to store data in a specific order for sequential processing.

A Queue works on the principle of FIFO - First In First Out, which means that the first item inserted into Queue will be first remove form Queue.

The adding of an item into queue is known as Enqueue operation, removing an item from queue is known as Dequeue operation and if an item only read from top of queue is known as Peek operation.

MethodDescriptions
Enqueue(object obj)For add an item in the Queue.
Dequeue()For remove an item from the Queue.
Peek()For retrieving an item without removing from the Queue.
Clear()For empty or removing all items from the Queue.

        // Add an item in queue

        queue.Enqueue("Asphelps");

 

        // Count total number of items in queue

        int total = queue.Count;  // output - 1

 

        // Retrieving top item form queue without removing it.

        queue.Peek();             // output - Asphelps

 

        // Remove item from queue

        queue.Dequeue();         // removed item Asphelps from queue

 

        // Clear the queue

        queue.Clear();          // empty the queue

 

        // Adding different data type in queue

        queue.Enqueue("Asphelps");     // Adding string type

        queue.Enqueue('A');            // Adding Char type

        queue.Enqueue(12);             // Adding int type

        queue.Enqueue(12.34);          // Adding double type

        queue.Enqueue(DateTime.Now);   // Adding DateTime type

 

        // Retrieving items from queue as FIFO

        // Dequeue() method not only return the item, but also remove the item from the queue

        while (queue.Count != 0)

        {

            Response.Write(queue.Dequeue());

            Response.Write("<br/>");

        }

        // Output

 

        //Asphelps

        //A

        //12

        //12.34

        //29-03-2014 14:39:47

Hashtable

HashTable stores any data type of items as key-value pairs. The data is stored in Hashtable basis of key and can be accessed by the key rather than index of items.

Each items in the HashTable in uniquely identified by it's key.

MethodDescriptions
Add(object key,object value)For add an item in the Hashtable.
Remove(object key)For remove an item from the Hashtable.
Clear()For empty or removing all items from the Hashtable.

        // Adding different data type in Hashtable

        // Remember that key should be unique

        // Key data type doesn't depends on data type of items

 

        hash.Add("asp","Asphelps");     // Adding string type

        hash.Add('h','A');              // Adding Char type

        hash.Add(1,12);                 // Adding int type

        hash.Add(1.1,12.34);            // Adding double type

        hash.Add(DateTime.Now.Month, DateTime.Now.Year);   // Adding DateTime type

 

        // Retrieving an item by using key

        Response.Write(hash["asp"]);  // output - Asphelps

        Response.Write(hash['h']);    // output - A

        Response.Write(hash[1]);      // output - 12

        Response.Write(hash[1.1]);    // output - 12.34

        Response.Write(hash[DateTime.Now.Month]);  // output - 2014

 

 

        // Retrieving all keys from Hashtable

        foreach (var key in hash.Keys)

        {

            Response.Write(key);

            Response.Write("<br/>");

        }

        // Output

 

        //asp

        //h

        //1.1

        //1

        //3 

 

        // Retrieving all items value from Hashtable

        foreach (var item in hash.Values)

        {

            Response.Write(item);

            Response.Write("<br/>");

        }

        // Output

 

        //Asphelps

        //A

        //12.34

        //12

        //2014

 

        // Count total number of items in Hashtable

        int total = hash.Count;

 

        // Remove an item from Hashtable by using key

        hash.Remove("asp");

 

        // Clear the Hashtable

        hash.Clear();

SortedList

A SortedList is a collection that contains key-value pairs. The data is stored in SortedList basis of key and it can be accessed by the key or the index and because of it is sorted.

Advantage of SortedList over Hashtable is that SortedList can access by it's index and it can sorted.

Use SortedList instead of Hashtable when keys of items are same data type.

MethodDescriptions
Add(object key, object value)For add an item in the SortedList.
GetByIndex(int index)For retrieve an item using from the SortedList.
GetKey(int index)For retrieve key of an item using index from the SortedList.
SetByIndex(int index,object value)For replace an item value by using index in the SortedList.
Remove(object key)For removing an item using item value from the SortedList.
RemoveAt(int index)For removing an item at specific index from the SortedList.
Clear()For empty or removing all items from the SortedList.

        // SortedList Decration

        SortedList sorted = new SortedList();

 

        // Adding different data type in SortedList

        // Remember that key should be unique

        // Key data type should be same type

 

        sorted.Add(1, "Asphelps");     // Adding string type

        sorted.Add(2, 'A');            // Adding Char type

        sorted.Add(3, 12);             // Adding int type

        sorted.Add(4, 12.34);          // Adding double type

        sorted.Add(5, DateTime.Now.Year);   // Adding DateTime type

 

        // Retrieving all keys from SortedList

        foreach (var key in sorted.Keys)

        {

            Response.Write(key);

            Response.Write("<br/>");

        }

        // Output

 

        //1

        //2

        //3

        //4

        //5       

 

        // Retrieving all items value from SortedList

        foreach (var item in sorted.Values)

        {

            Response.Write(item);

            Response.Write("<br/>");

        }

        // Output

 

        //Asphelps

        //A

        //12

        //12.34

        //2014

 

        // Count total number of items in SortedList

        int total = sorted.Count;

 

        // Retrieving item value by using index

        sorted.GetByIndex(0);  //output - Asphelps

 

        // Retrieving item value by using key

        sorted.GetKey(1);  // output - Asphelps

 

        // Replace the item value by using index

        sorted.SetByIndex(0, "asp-helps"); // it will replace "Asphelps" by "asp-helps"

 

        // Remove an item from SortedList by using key

        sorted.Remove(1); // remove item which has key value 1  i.e. first item form the SortedList

 

        // Remove a specific index item from SortedList

        sorted.RemoveAt(1);  // remove item which is at index 1 position i.e. 2nd item

 

        // Clear the SortedList

        sorted.Clear();



Please give your feedback for improving this page