Introduction
In this article I will explain on Collections especially classes that is in System.Collections Namespace in .NET Framework. Some of the Collection objects that I will explain include Arrays, ArrayList, SortedList, Hashtables, Queues , Stacks, and Lists.
As you all probably has heard and use all of these in OO languages or non OO languages. Collections has been used by all programmers regardless of programming languages in the world and whether you realize it or not, you are using it every day when you are doing programming. In the first section, I will explain about Arrays
Arrays
The simplest collection of objects in programming languages is an Array. You can insert an objects into an array or even a collection of basic primitive types such as integer, double, strings.
In this example,lets start inserting Collection of Person objects into an Array
Code Sample (A Simple Person Class)
public class Person {
string FirstName;
string LastName;
public Person (string first,string Last) {
FirstName = first;
LastName = last;
}
public string FirstName {
get{
return FirstName + " " + LastName;
}
}
}
Inserting People objects in Arrays Collections public partial class _Default :System.Web.UI.Page {
protected void Page_Load(object sender,EventArgs e) {
Person michael = new Person("Michael","Jackson");
Person bill = new Person("Bill","Gate");
Person michelle = new Person("Michelle","Sullivan");
Person[] people = new Person[3];
people[0] = michael;
people[1] = bill;
people[2] = michelle;
//Using For Each to print out the Objects from Array
foreach (Person p in people) {
Response.Write(p.FullName + " <BR>");
}
//Using ForLoop to print out the objetcs from Array
for(int i=0;i < people.Length;i++) {
Response.Write(people[i].FullName + " <BR>");
}
}
}
The result of this very simple code is shown below
Michael Jackson
Bill Gate
Michelle Sullivan
Note that the results are the same for ForLoop and ForEach loop. This is because the ForEach compiled Intermediate code is almost the same with the For Loop and you can reap the benefits without have to worry about the array index and your code will be much easier to read.
Resizing Arrays
VB language can resize an array and keep the existing values with the ReDim statement. Here you can double the size of the people array by using ReDim.
e.g ReDim Preserve people (5)
In C#, it doesn't support a convenient array resizing statement such as ReDim. Instead you copy people to a larger new array.
Code sample below
Person[] people2 = new Person[8];
Array.Copy(people,people2,people.Length);
Finding Objects in Arrays
Searching objects from the array is quite easy and straight forward in .NET framework.
int indexOfMichael = Array.IndexOf(people,michael);
Response.Write ("Michael is at " + indexOfMichael + ");
Sorting Objects in Arrays
For objects to have the sorting features, it needs to implement the IComparable interface and the IComparable interface basically consists of one method that is called CompareTo(). The CompareTo Method will basically return 3 values to determine which object is greater than the other objects being compared.
It will return 0, if both objects are equal.
It will return less than 0, if current object is less than the other object.
It will return greater than 0 , if current object is greater than the other object.
In our Person class, We can try to do a sorting based on the Age. Since Age is an Integer objects and Integer objects already implement the CompareTo methods, we can make use of this to compare two instance of the Person objects based on the Age. Below is the sample code.
public class Person:IComparable {
string FirstName;
string LastName;
int iAge;
public Person (string first,string Last,int age) {
FirstName = first;
LastName = last;
Age = age;
}
public string FirstName {
get{
return FirstName + " " + LastName;
}
}
public int Age {
get {
return iAge;
}
}
int iComparable.CompareTo(object obj) {
Person p2 = obj as Person;
if(p2 == null) throw new ArgumentException("Object is not a Person");
int iAgeCompared = this.Age.CompareTo(p2.Age);
return iAgeCompared;
}
}
Now to do the Sorting, you can use static method from Array class called Sort. Person michael = new Person("Michael","Jackson",12);
Person bill = new Person("Bill","Gate",11);
Person michelle = new Person("Michelle","Sullivan",14);
Person[] people = new Person[3];
people[0] = michael;
people[1] = bill;
people[2] = michelle;
//Before Sorted
foreach (Person p in people) {
Response.Write(p.FullName + " <BR>");
}
//After Sorted
Array.Sort(people);
foreach (Person p in people) {
Response.Write(p.FullName + " <BR>");
}
The Array.Sort method is a Static method that returns a void. That means that it sorts the Array that you passed in as a parameter in place. The method doesn't return an array. Notice that after you call the Array.Sort method, the list is correctly sorted based on the Age. This is because we have already implemented the IComparable interface.
ArrayList
If you have all the trouble and error when working and dealing with the size of the Array. Then ArrayList might be perfect for you. You don't have to worry about the Array size, as ArrayList has the features for automatic sizing. You have all the helper methods called Add,Insert,Remove,Sort. The only downside of the ArrayList is you have to type cast the objects upon retrieval from the Array.
public partial class _Default:System.Web.UI.Page
{
protected void Page_Load(object sender,EventArgs e)
{
Person michael = new Person("Michael","Jackson",12);
Person bill = new Person("Bill","Gate",11);
Person michelle = new Person("Michelle","Sullivan",14);
ArrayList people = new ArrayList();
people.Add(michael);
people.Add(bill);
people.Add(michelle);
//Using ForEach to print people
foreach(Person p in people) {
Response.Write(p.FullName + " <BR>");
}
//Sorting
people.Sort();
foreach(Person p in people) {
Response.Write(p.FullName + " <BR>");
}
//Search By index
int indexOfMichael = people.IndexOf(michael);
Response.Write("Index Of Michael is " + indexOfMichael);
}
}
Hashtables
If you like to store a collection of objects but with the key and value pair, then the Hashtable might be the best choice for you. Hashtable allow you to retrieve the objects based on the key you specified. It can be a string or integer. Unlike an array, you can only retrieve the value only by the index.
protected void Page_Load(object sender,EventArgs e) {
Person michael = new Person("Michael","Jackson",12);
Person bill = new Person("Bill","Gate",11);
Person michelle = new Person("Michelle","Sullivan",14);
Hashtable ht = new Hashtable();
ht.Add("mc",michael);
ht.Add("bl",bill);
ht.Add("me",michelle);
Person hashtablePerson = (Person)ht["sh"];
Response.Write(hashtablePerson.FullName);
}
Queues and Stacks
Queus and Stacks are almost the inverse of each other. Queues are great for storing objects in the order in which they arrive, whereas a Stack is a first in last out Structure.
Queue oQueue = new Queue();
oQueue.Enqueue(michael);
oQueue.Enqueue(bill);
oQueue.Enqueue(michelle);
Person x = (Person)oQueue.Dequeue();
Response.Write(x.FullName + "<BR>);
x = (Person)oQueue.Dequeue();
Response.Write(x.FullName + "<BR>);
x = (Person)oQueue.Dequeue();
Response.Write(x.FullName + "<BR>);
Because a Queue is a first in, first out structure, the Person objects print in the same order that they were enqueued into the Queue.
Output of the Code
Michael Jackson
Bill Gate
Michelle Sullivan
Stacks are first in, last out. One pushes objects onto a stack and pops them off the stack. If you imagine literally stacking objects on top of each other, you see that the analogy works. Stacks also include a very useful function called Peek, that lets you see the object at the top of the Stack without removing it
Stack oStack = new Stack();
oStack.Push(michael);
oStack.Push(bill);
oStack.Push(michelle);
Person x = (Person)oStack.Pop();
Response.Write(x.FullName + "<BR>);
Person x = (Person)oStack.Pop();
Response.Write(x.FullName + "<BR>);
Person x = (Person)oStack.Peek();
Response.Write(x.FullName + "<BR>);
Person x = (Person)oStack.Pop();
Response.Write(x.FullName + "<BR>);
Output of the listing below
Michelle Sulivan
Bill Gate
Michael Jackson
Michael Jackson