Working with C# Collections

Computer programming is all about working with data. Data can be of various types and kinds and take multiple shapes and forms, but with the help of programming languages we are able to manage them seamlessly. In this article we are going to take a look at what collections are all about and how to implement them in C#. For now it’s enough if you know that under collections we understand data that’s grouped together.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 24
December 16, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement
Fortunately, ever since its first version, the .NET Framework has given programmers a healthy amount of built-in collections classes along with numerous methods that allow us to easily manipulate the data stored within. Of course, we can also write our own collections, but throughout this article we are going to focus on what’s already been done and is ready to use. We need to understand when and how to use each.

At the beginning we will see the foundation on which each collection class lies. It’s really important to understand the interface on which they are based: IEnumerable and its ICollections extension. From the latter there are two other interfaces derived: IList and IDictionary. The collections classes which are built into the System.Collections namespaces are always implementing each of the aforementioned interfaces. However, keep in mind that there are other interfaces too (e.g.; IEnumerator, IComparer, etc.).

Before we move on, here’s a list of collection classes that are going to be covered within this brief tutorial article: Queue, Stack, BitArrays, ArrayList, StringCollection, Hashtable, SortedList, ListDictionary, StringDictionary, and so forth. There are so-called generic classes which can be reached via the System.Collections.Generic namespace, but they are strongly typed collections.

Now we are ready to move on. Once again, to eliminate all kinds of problems be sure to include the following namespaces into your test projects on which you are going to be working while reading this article: System.Collections, System.Collections.Generic, and System.Collections.Specialized. But it’s worth taking a glance over the official documentation to see which one you’re going to need.

Various Collections

To begin with, under the term "collection" in computer science, we understand the grouping of data types that share some familiarity or significance, and with which we are able to work using the same techniques and strategies to manipulate the data stored within. Collections, unlike arrays for example, do not store a fixed amount of items.

Now it’s time to introduce and explain a few new programming terms. The main problem is that they sound similar but the differences are huge. First off, we call sets those kinds of data array types where the order is important. Sequential access is important because that’s how we move through the items. Sorting operations on lists are frequent.

Other kinds of data array collections generally sport index-based accessing. Random access is the main advantage compared to lists. In this section we can include collection classes such as the Hashtable, SortedList, ListDictionary, and generic classes. Fast searches and information retrieval are given by ListDictionary along with Hashtable.

The first collection class that we are going to present here is the ArrayList. It’s based on IList and offers a lot of benefits compared to traditional old-school arrays, mostly because you can add new items anywhere (inside the list, at the end of the list, etc.), delete items, sort the list, check whether one item exists, and so forth. Most importantly, its size is dynamically increased, so you don’t have to worry about that.

Declaring a new pointer can be done using the ArrayList() constructor; of course, the type of the data is also ArrayList. Once we’re done with this, we are able to add new items using the Add() method. We can sort the list with the Sort() function but also reverse using Reverse(). The count of items is returned using Count() property. Retrieving items can be done using Item[] and specifying the index within the brackets.

The example below will surely make sense and illustrate the above explanation.

using System;

using System.Collections;

public class SampleProgram{

public static void Main(){

ArrayList testArray = new ArrayList();

testArray.Add(3);

testArray.Add(7);

testArray.Add(2);

testArray.Add(5);

foreach (int n in testArray)

Console.WriteLine(n.ToString());

testArray.Sort();

testArray.Remove(5);

testArray.Add("ASP Free");

for (int i = 0; i < testArray.Count; i++)

Console.WriteLine(testArray[i]);

Console.WriteLine("Count: {0}", testArray.Count);

Console.WriteLine("Capacity: {0}", testArray.Capacity);

}

}

The output of the above program is the following. Please keep in mind that we are handling the writing out on the console in two different ways. The first one handles only ints because we declare a new int n which gets looped through the entire collection, while in the latter case we are using the int i as an index to refer to the collection’s items.

3

7

2

5

2

3

7

ASP Free

Count: 4

Capacity: 4

Another collection class that we are going to present here is the Stack. This sort of class gives us “Last in, First Out” (abbreviated as LIFO) dominant behavior. This means that this order, according to which we can access and work with the elements, is given. In short, we can put items only on the top of the stack; likewise we can remove only those that are located there as well.

The main difference compared to the built-in methods of ArrayList here is that the two major methods of the Stack class are called Push() and Pop(). These terms are quite common in computer science, and you shouldn’t be surprised if you know that these are taken for granted and “universal” in other languages too (e.g.; C++ STL.). A new item can be placed on the stack’s top with Push, while Pop removes the top item.

It should be noted that you do not need to manually increase the index counter since this is automatically managed by the compiler. After each pop or push task the compiler decreases or increases that Count property, respectively. Moreover, the Stack has a constructor to which you can pass over, as an argument, other collection class variables. For example, you can create a stack out of an ArrayList.

On the next page you will see another code snippet exemplifying the above explanation.

Tell Me More!

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.

Final Thoughts

Now that you have arrived at this page, you have successfully acquired this necessary snippet of knowledge for your coding arsenal. Working with collections in order to store different kinds of data into built-in collection classes instead of being required to write your own data types and objects is always a time-saver. Due to space restrictions we couldn’t cover custom collections, but check out this damn great guide.

C# is definitely one of those languages that was designed for the lazier type of programmers. Sure, some call it a language for typical rapid application development, but in reality it’s all about making your overall tasks easier, faster, and therefore, increasing your productivity. Knowing when and how to use the right type of collections will surely boost your efficiency.

Furthermore, don’t forget to head over to the MSDN Library every once in a while because newer Framework releases can open up lots of opportunities by expanding the list of built-in functions, methods, types, and who knows what else. We must face it, programming advances with the speed of technology and if we can’t keep up with its pace, we get outdated and lose a big chunk of productivity.

As a finale, I’d like to invite you to join our ever-growing and friendly community of technology professionals at Dev Hardware Forums. We focus on all areas of IT&C starting from hardware, software, and going up to consumer electronics and around-the-clock IT news. You might also want to check out the forums of our sister site at ASP Free which focuses on Microsoft content.

Take care!

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 2 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials