Collections

Arrays in C#?

  • An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations.
  • Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
  • All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays

To declare an array in C#, you can use the following syntax :

datatype[] arrayName;

where,

  • datatype is used to specify the type of elements in the array.
  • [ ] specifies the rank of the array. The rank specifies the size of the array.
  • arrayName specifies the name of the array.

Initializing Arrays

Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.

Array is a reference type, so you need to use the new keyword to create an instance of the array.

double[] balance = new double[10];

Assigning Values to an Array

You can assign values to individual array elements, by using the index number, like

double[] balance = new double[10];
balance[0] = 4500.0;

You can assign values to the array at the time of declaration, as shown

double[] balance = { 2340.0, 4523.69, 3421.0};

You can also create and initialize an array, as shown

int [] marks = new int[5]  { 99,  98, 92, 97, 95};

You may also omit the size of the array, as shown

int [] marks = new int[]  { 99,  98, 92, 97, 95};

Accessing Array Elements

using System;

namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int []  n = new int[10]; /* n is an array of 10 integers */
         int i,j;

         /* initialize elements of array n */ 
         for ( i = 0; i < 10; i++ ) { //Setting the array with values from 100 to 109
            n[ i ] = i + 100;
         }
         
         /* output each array element's value */
         for (j = 0; j < 10; j++ ) { //Traversing through the array to display the values
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}

Collections in C#?

  • Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces.
  • Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#.

The following are the various commonly used classes of the System.Collection namespace :

  • ArrayList
  • HashTable
  • Stack
  • Queue

ArrayList

It represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However, unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, adding, searching and sorting items in the list.

Example

using System;
using System.Collections;

namespace CollectionApplication {
   class Program {
      static void Main(string[] args) {
         ArrayList al = new ArrayList(); //Instantiating an ArrayList 
         
         Console.WriteLine("Adding some numbers:");
         al.Add(45); //Adding elements into the ArrayList
         al.Add(78);
         al.Add(33);
         al.Add(56);
         al.Add(12);
         al.Add(23);
         al.Add(9);
         
         Console.WriteLine("Capacity: {0} ", al.Capacity);
         Console.WriteLine("Count: {0}", al.Count);
         
         Console.Write("Content: ");
         foreach (int i in al) { //Traversing through an ArrayList
            Console.Write(i + " ");
         }
         
         Console.WriteLine();
         Console.Write("Sorted Content: ");
         al.Sort(); //Sorting an ArrayList
         foreach (int i in al) {  //Traversing through an ArrayList
            Console.Write(i + " ");
         }
         Console.WriteLine();
         Console.ReadKey();
      }
   }
}

HashTable

  • The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection.
  • A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.

Example

using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         Hashtable ht = new Hashtable(); //Instantiating a HashTable
         
         ht.Add("001", "Zara Ali"); //Adding elements into the HashTable
         ht.Add("002", "Abida Rehman");
         ht.Add("003", "Joe Holzner");
         ht.Add("004", "Mausam Benazir Nur");
         ht.Add("005", "M. Amlan");
         ht.Add("006", "M. Arif");
         ht.Add("007", "Ritesh Saikia");
         
         if (ht.ContainsValue("Nuha Ali")) { //Checks if a value is in the HashTable
            Console.WriteLine("This student name is already in the list");
         } else {
            ht.Add("008", "Nuha Ali"); //If not adds the value to the HashTable
         }
         
         // Get a collection of the keys.
         ICollection key = ht.Keys; //Get the keys alone
         
         foreach (string k in key) { //Traverse and display the keys & value
            Console.WriteLine(k + ": " + ht[k]);
         }
         Console.ReadKey();
      }
   }
}

Stack

It represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item.

Example

using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         Stack st = new Stack(); //Instantiating a Stack
         
         st.Push('A'); //Pushing items to the top of the stack
         st.Push('M');
         st.Push('G');
         st.Push('W');
         
         Console.WriteLine("Current stack: ");
         foreach (char c in st) { //Traversing through the stack
            Console.Write(c + " ");
         }
         Console.WriteLine();
         
         st.Push('V'); //Adding more items to the stack {V,W,G,M,A} - current state
         st.Push('H'); //Adding more items to the stack {H,V,W,G,M,A} - current state
         Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
         Console.WriteLine("Current stack: ");
         
         foreach (char c in st) { //Traversing through the stack
            Console.Write(c + " ");
         }
         
         Console.WriteLine();
         
         Console.WriteLine("Removing values ");
         st.Pop(); //Popping elements from the top of the stack {H}
         st.Pop(); //Popping elements from the top of the stack {V}
         st.Pop(); //Popping elements from the top of the stack {W}
         
         Console.WriteLine("Current stack: ");
         foreach (char c in st) { //Traversing through the stack {G,M,A}
            Console.Write(c + " ");
         }
      }
   }
}

Queue

It represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque.

Example

using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         Queue q = new Queue(); //Instantiating a Queue
         
         q.Enqueue('A'); //Adding elements into a Queue
         q.Enqueue('M'); //Adding elements into a Queue
         q.Enqueue('G'); //Adding elements into a Queue
         q.Enqueue('W'); //Adding elements into a Queue {A,M,G,W} - current state
         
         Console.WriteLine("Current queue: ");
         foreach (char c in q) Console.Write(c + " "); //Traversal using foreach loop
         
         Console.WriteLine();
         q.Enqueue('V'); //Adding elements into a Queue
         q.Enqueue('H'); //Adding elements into a Queue {A,M,G,W,V,H} - current state
         Console.WriteLine("Current queue: ");
         foreach (char c in q) Console.Write(c + " "); //Traversal using foreach loop
         
         Console.WriteLine();
         Console.WriteLine("Removing some values ");
         char ch = (char)q.Dequeue(); //Removing elements from queue {A}
         Console.WriteLine("The removed value: {0}", ch);
         ch = (char)q.Dequeue(); //Removing elements from queue {M}
         Console.WriteLine("The removed value: {0}", ch);
         
         Console.ReadKey();
      }
   }
}