C# Collections


To construct and manipulate a collection of objects, .Net framework has provided us with many classes. ArrayList, BitArray, HashTable, SortedList, Queue and Stack are some of them. They are all included in System.Collections namespace.

Download myQueue.cs

Download myStack.cs

In general, Arrays are not dynamic in nature and do not allow the user to remove an element easily. An ArrayList is like an expandable array of objects. Its Add, Insert, Remove RemoveAt methods make it relatively easy to insert and remove elements from the ArrayList. But we cannot refer to an entry in an ArrayList by a key. HastTable solves this problem but it does not allow its entries to be addressed using indexes. It also does not allow us to retrieve the entries in any particular order. SortedList represents a collection of associated keys & values. The values are sorted by key and are accessible by key and by Index.

The purpose of this paper is to demonstrate the use of stack and Queue classes, identify their key strengths and limitations. This paper first explains the stack/queue concept and then applies the concept to an example. The program is explained with the help of comment lines.

STACK

Stack class is generally referred to as LIFO (Last In First Out). The best example could be "a stack of plates in the fabrication company". The last plate placed on the stack is the first one to be removed. Stack in implemented as circular buffer. The various methods of stack class are

Push
Inserts an object at the top of the Stack

Pop
Returns and permanently removes the object at the top of the Stack

Peek
Returns the object at the top of the Stack without removing it

Clear
Clears the stack by removing all objects from the Stack

Clone
Creates a shallow copy of the Stack

CopyTo
Copies the Stack to an existing one-dimensional Array

ToArray
Copies the Stack to a new array

Contains
Determines if an element is present in the Stack

Equals
Determines if two Object instances are equal

ToString
Returns a String that represents the current Object

GetEnumerator, GetHashCode and GetType are also some of the methods of stack class.
Count, IsReadOnly, IsSynchronized, SyncRoot are the properties of Stack class.

The initial capacity is the starting capacity of the new stack. Once current capacity is reached, the capacity is doubled. The default initial capacity is 10. Almost all the methods of Stack class, except Synchronized method are virtual and can be overridden by the derived class. Stack is not thread-safe, To guarantee thread safety of a stack, all operations must be done through the wrapper returned by the Synchronized method.

Example using Queue

pic1 C# Collections

The Code

// This example uses all the important methods of a stack class
using System;
using System.Collections;
public class myStack
{
public static void Main()
{ // Create and instantiate new Stack
Stack myStack = new Stack();
// Adding 4 objects to the stack
myStack.Push("Vijay");
myStack.Push("Vikas");
myStack.Push("Emill");
myStack.Push("Rajiv");
// Create and initialize one-dimensional Array
Array myArray=Array.CreateInstance(typeof(String),15);
// Add 5 elements to the array
myArray.SetValue("student1", 0);
myArray.SetValue("student2", 1);
myArray.SetValue("student3", 2);
myArray.SetValue("student4", 3);
myArray.SetValue("student5", 4);
// Count the number of objects in the stack
Console.Write("Total number of objects in the stack : " );
Console.Write(myStack.Count);
// Print all the objects in the stack
Console.Write("\nThe objects are :");
PrintValues(myStack);
Console.WriteLine();
Console.WriteLine("\tObject no \t3\t2\t1\t0");
// Remove an element from the stack (Last In First Out)
Console.WriteLine();
Console.WriteLine("Pop removes&shows Last element of the stack first");
Console.Write("The element removed is : " );
Console.Write("\t{0}", myStack.Pop());
// Show an element from the stack
Console.WriteLine("\nPeek method just shows an element but does not
remove it from the stack");
Console.Write("The element shown is : " );
Console.Write("\t{0}", myStack.Peek());
Console.WriteLine();
// Count and print the number of objects in the stack
Console.Write("\nTotal remaining number of objects in the stack : " );
Console.Write(myStack.Count);
Console.WriteLine();
Console.Write("\nThe objects are :");
PrintValues(myStack);
Console.WriteLine();
Console.WriteLine("\tObject no \t2\t1\t0");;
// Clear the Stack.
myStack.Clear();
Console.WriteLine();
Console.Write("The stack is cleared. Now, total number of objects = ");
Console.Write(myStack.Count);
Console.WriteLine();
// Refill the stack with different values
myStack.Push("Patil");
myStack.Push("Agarwal");
myStack.Push("Tsankov");
myStack.Push("Gomes");
myStack.Push("Smith");
// Count and print the number of objects in the stack
Console.WriteLine();
Console.Write("Total number of NEW objects in the stack : " );
Console.Write(myStack.Count);
Console.WriteLine();
Console.Write("\nThe objects are :");
PrintValues(myStack);
Console.WriteLine();
Console.WriteLine("\tObject no \t4\t3\t2\t1\t0");
Console.WriteLine();
// Display the values of the target Array instance.
Console.WriteLine("The target Array contains following elements BEFORE
copying):" );
PrintValues(myArray,' ');
// Copy the entire source Stack to target Array, starting at index 3.
myStack.CopyTo( myArray, 3 );
Console.WriteLine();
Console.WriteLine("The target Array contains following elements AFTER
copying):" );
PrintValues(myArray,' ');
}

public static void PrintValues(Array myArr, char mySeparator)
{ System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
int i = 0;
int cols = myArr.GetLength( myArr.Rank – 1 );
while ( myEnumerator.MoveNext() )
{ if ( i < cols )
{ i++; }
else {Console.WriteLine();i = 1;}
Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
}
Console.WriteLine();
}

public static void PrintValues( IEnumerable myCollection )
{ System.Collections.IEnumerator myEnumerator =
myCollection.GetEnumerator();
while ( myEnumerator.MoveNext() )
Console.Write( "\t{0}", myEnumerator.Current );
}
}

QUEUE

Queue is another collection class in C#. Unlike Stack, it allows the first object entered to pop out first. A queue is referred to as FIFO (First in First Out). The best analogy for Queue is "a queue for any ticket counter, the first one to get in the queue gets first chance". The three main methods utilized are Enqueue, Dequeue and Peek.

Peek Returns the object at the beginning of the Queue without removing it.
Dequeue Removes and returns the object at the beginning of the Queue.
Enqueue Adds an object to the end of the Queue.

Clear, Clone, Contains, CopyTo, ToArray, ToString, Equals, GetEnumerator, GetHashCode, GetType methods have the meaning as that in Stack class. Count, IsReadOnly, IsSynchronized, SyncRoot are the properties of Stack class.

Example using Queue

pic2 C# Collections

The Code

// This example uses all the important methods of a queue class
using System;
using System.Collections;
public class myQueue
{
public static void Main()
{ // Create and instantiate new queue
Queue myQueue = new Queue();
// Adding 4 objects to the Queue
myQueue.Enqueue("Vijay");
myQueue.Enqueue("Vikas");
myQueue.Enqueue("Emill");
myQueue.Enqueue("Rajiv");
// Create and initialize one-dimensional Array
Array myArray=Array.CreateInstance(typeof(String),15);
// Add 5 elements to the array
myArray.SetValue("student1", 0);
myArray.SetValue("student2", 1);
myArray.SetValue("student3", 2);
myArray.SetValue("student4", 3);
myArray.SetValue("student5", 4);
// Count the number of objects in the queue
Console.Write("Total number of objects in the queue : " );
Console.Write(myQueue.Count);
Console.WriteLine();
// Print all the objects in the stack
Console.Write("\nThe objects are :");
PrintValues(myQueue); Console.WriteLine();
Console.WriteLine("\tObject no \t0\t1\t2\t3");
// Remove an element from the queue (First In First Out)
Console.WriteLine();
Console.WriteLine("Dequeue method removes and shows FIRST element from
the queue FIRST ");
Console.Write("The element removed is : " );
Console.Write("\t{0}", myQueue.Dequeue());Console.WriteLine();
// Show an element from the queue
Console.WriteLine("\nPeek method just shows an element but does not
remove it from the queue");
Console.Write("The element shown is : " );
Console.Write("\t{0}", myQueue.Peek());
// Count and print the number of objects in the stack
Console.WriteLine();
Console.Write("\nTotal remaining number of objects in the queue : " );
Console.Write(myQueue.Count);
Console.WriteLine();
Console.Write("\nThe objects are :");
PrintValues(myQueue);
Console.WriteLine();
Console.WriteLine("\tObject no \t0\t1\t2");
Console.WriteLine();
// Clear the Stack.
myQueue.Clear();
Console.Write("The queue is cleared. Now, total number of objects = ");
Console.Write(myQueue.Count);
Console.WriteLine();
// Refill the stack with different values
myQueue.Enqueue("Patil");
myQueue.Enqueue("Agarwal");
myQueue.Enqueue("Tsankov");
myQueue.Enqueue("Gomes");
myQueue.Enqueue("Smith");
// Count and print the number of objects in the stack
Console.WriteLine();
Console.Write("Total number of NEW objects in the stack : " );
Console.Write(myQueue.Count);
Console.WriteLine();
Console.Write("\nThe objects are :");
PrintValues(myQueue);
Console.WriteLine();
Console.WriteLine("\tObject no \t0\t1\t2\t3\t4");
// Display the values of the target Array instance.
Console.WriteLine();
Console.WriteLine( "The target Array contains following elements BEFORE
copying):" );
PrintValues(myArray,' ');
// Copy the entire Stack to an Array instance, starting at index 3.
myQueue.CopyTo( myArray, 3 );
Console.WriteLine();
Console.WriteLine( "The target Array contains following elements AFTER
copying):" );
PrintValues(myArray,' ');
}

public static void PrintValues(Array myArr, char mySeparator)
{ System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
int i = 0;
int cols = myArr.GetLength( myArr.Rank-1);
while ( myEnumerator.MoveNext())
{
if ( i < cols )
{ i++; }
else
{ Console.WriteLine(); i = 1; }
Console.Write("{0}{1}", mySeparator, myEnumerator.Current);
}
Console.WriteLine();
}

public static void PrintValues( IEnumerable myCollection )
{ System.Collections.IEnumerator myEnumerator =
myCollection.GetEnumerator();
while ( myEnumerator.MoveNext() )
Console.Write( "\t{0}", myEnumerator.Current );
}
}

REFERENCES

1. Professional C# by Simon Robinson et al.
2. MSDN Documentation from http://msdn.microsoft.com/net.
3. http://www.securedomains.com/news/XcNewsPlus.asp?cmd=view&articleid=24

Related Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!