Working with C# Collections - Tell Me More!
(Page 3 of 4 )
All right, on the previous page we promised an example with Stack, but before we arrive there, there’s still one more thing to say. The Stack is also based on the IEnumerable interface; thanks to this, we can simply go through its elements using a de facto standard foreach loop. This is the simplest, but there are alternatives.
The Stack collection class also contains a healthy amount of useful methods and properties that can save us time. Let’s enumerate a few: Clone() creates a shallow copy of the stack indifferent of whether the data is of reference type of value; the Peek() method returns the element that is located on the top of the stack but it does not get removed (a la taking a peek); ToArray() copies the stack to an array, and so forth.
using System;
using System.Collections;
public class SampleProgram2{
public static void Main(){
Stack testStack = new Stack();
testStack.Push("developer");
testStack.Push("shed");
testStack.Push(10);
testStack.Push(50);
while (testStack.Count > 0){
Console.WriteLine("Peeking " + testStack.Peek() + " element");
testStack.Pop();
}
}
}
And the output of the above code snippet is the following.
Peeking 50 element
Peeking 10 element
Peeking shed element
Peeking developer element
Working with NameValueCollection classes is really straightforward because there is barely any difference from the ones presented until now. Basically, their scheme is typically of name strings, and to each there is linked another value string. This means we can add new elements in the following fashion:
testNameValueCol.Add("developer", "shed");
Furthermore, to retrieve data you can use Get(), GetKey(), GetType(), GetValues() and various other methods as well. Don’t hesitate to head over to the official MSDN documentation, because each is explained thoroughly along with examples.
For instance, in the above example, calling GetKey() on the first index would return developer while Get() on the same very first index would return shed. Nevertheless, you can iterate through the NameValueCollection with foreach if you use the AllKeys (which gets all keys enclosed within).
Finally, we are going to cover two more collection classes. First I will explain the queue class, which should definitely be known since it is just as important as the stack. And in the end, we will finish this article with StringDictionary. The main difference with the former is that instead of objects, the type of data must be string. But in their very basic form, they are hash tables that are limited to strongly typed strings (both the key and its value).
Declaring queues is just as easy as stacks. We do it by creating a new Queue. Adding new objects can be done using the Enqueue() method. The easiest analogy to help you imagine queues is to picture standing in line at a hypermarket. It is based on the FIFO—‘First in, First Out’ concept. The person that arrived earlier gets out the fastest. Simple!
Once again, Queue sports a constructor that accepts ICollection implementers outright as arguments just as stacks did. This means we can create queues out of ArrayLists, BiteArrays, and so forth -- basically all kinds of collections that are based on the ICollection interface. The Peek() method can be used to retrieve items from the queue. Don’t forget that the “first” item can always be retrieved (FIFO, remember!).
The Dequeue() method removes the first item from the queue. The Clear() method simply clears all of its elements, just as it works on all of the collections. Moreover, you can also use the foreach loop to iterate through a queue’s elements. Just be careful when you use cast because the items aren’t returned as you’d expect.
As promised, let’s also see how to work with StringDictionary collection classes. By now you shouldn’t have any problems with declaring a new collection class, so we’ll skip that part. Moving on, you can also use the Add() method here that takes any string argument. Keep in mind, a StringDictionary collection is a hash table that accepts only strings as keys and its values.
Iterating through its elements can be done with foreach. But in order to retrieve data you can use properties such as the Keys and Values (they each return collections). The Count property always holds the total number of key/value pairs contained within. The ContainKey() and ContainsValue() in-built functions can be used to determine whether a key or value can be found inside the collection. Both of them return a Boolean.
Next: Final Thoughts >>
More C# Articles
More By Barzan "Tony" Antal