• Now Online : 86
  • admin@codemyne.net


In the previous article Collections in C#.Net we have learnt about ArrayLst, Hashtable and their usage. Remaining classes in collections are SortedList, BitArray, Queue, Stack.

SortedList: The SortedList contains items in key/value pairs. A SortedList automatically sort the items in alphabetic or numeric order.

  • A SortedList can be sized to its final size with the TrimToSize() method.
  • A SortedList does not allow duplicate keys.
  • Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting.
SortedList slCountries = new SortedList();
slCountries.Add("I", "India");
slCountries.Add("U", "USA");
slCountries.Add("F", "France");
slCountries.Add("J", "Japan");
for (int i = 0; i < slCountries.Count; i++)
    Console.WriteLine("\t{0}:\t{1}", slCountries.GetKey(i), slCountries.GetByIndex(i));

BitArray: Manages an array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).

  • The size of a BitArray is controlled by the client. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
BitArray ba = new BitArray(5);
ba[0] = true;
ba[1] = false;
ba[2] = true;
for (int i = 0; i < ba.Count; i++)
IEnumerator ie;
ie = ba.GetEnumerator();
while (ie.MoveNext())

Queue: Represents a first-in, first-out (FIFO) collection of objects.

  • Queues are useful for storing messages in the order they were received for sequential processing.
  • This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other.
  • The capacity of a Queue is the number of elements the Queue can hold.
  • As elements are added to a Queue, the capacity is automatically increased as required through reallocation.
  • Queue accepts null as a valid value and allows duplicate elements.
Queue q = new Queue(); 
q.Enqueue("data 1"); 
q.Enqueue("data 2"); 
q.Enqueue("data 3"); 
foreach (Object var in q)             
IEnumerator ie;
ie = q.GetEnumerator();            
while (ie.MoveNext()) 

Stack: Represents a simple last-in-first-out (LIFO) non-generic collection of objects.

  • Stack is implemented as a circular buffer. The capacity of a Stack is the number of elements the Stack can hold.
  • As elements are added to a Stack, the capacity is automatically increased as required through reallocation.
// Creates and initializes a new Stack.
Stack st = new Stack();
foreach (object var in st)
// using IEnumerator
IEnumerator ie;
ie = st.GetEnumerator();
while (ie.MoveNext())

Comments/Suggestions are invited. Happy coding......!

Comments Post a Comment