C# Generic Collections: An Introduction
The ‘List’ Collection
The List collection is kind of a super-array. It inherits from a number of interfaces: IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable. I’m not going to go into great detail about the methods and properties in these interfaces; needless to say they are all implemented in the List class.
There is probably only one method you will use every time you use the List method: ‘Add’. To illustrate, here is how you would create and instantiate an object of the List type, storing String objects, and use the ‘Add’ method to include some elements within it:
[FONT="] [COLOR=#2B91AF]List[/COLOR]<[COLOR=#2B91AF]String[/COLOR]> myStringList = [COLOR=blue]new[/COLOR] [COLOR=#2B91AF]List[/COLOR]<[COLOR=#2B91AF]String[/COLOR]>();[/FONT] [FONT="] myStringList.Add([COLOR=#A31515]"This is the first item in my list!"[/COLOR]);[/FONT]
First, let’s take a look at the syntax of our statements. In the first token of the first statement, after the word ‘List’ we have the type we want to store in our list enclosed in angle brackets. This is synonymous with the type placed before the pair of square brackets in the declaration of a normal array.
We’ve used the default constructor for the class. There are also two other constructors for the class, one that takes a single integer and creates enough space for that many objects of storage type; and one that takes another collection (any collection that implements the IEnumerable<T> interface – which most collections do) as its only parameter, and then copies all the elements of that collection to the list. All of these constructors are useful in different situations but the default constructor is the easiest to deal with, especially if you’re starting with an empty List and you’re unsure of how many elements the List will contain when it reaches its highest capacity during its lifetime.
Now, let’s talk about capacity. With a List object, there is no need to set a capacity as with an array because the object grows automatically as more elements are added. In terms of the space that is reserved however, when we instantiate a List object, enough space is reserved for four elements. When a total of four elements have been added the capacity doubles in size, to eight, and the capacity continues to double every time that the maximum number of elements is reached.
The property ‘Capacity’ returns the current number of elements that the List can hold. Additionally, it’s possible to remove the excess space from your List (ie. the total space minus total elements – or ‘Capacity’ minus ‘Count’) use the TrimExcess() method.
Moving on, let’s take a look at some other operations we can perform on List objects. First, let’s look at the obvious ones:
Clear() – Removes all elements from the list. Handy if you want to repopulate a list on the fly rather than create a new list or mix elements etc.
Contains(T item) – Returns a Boolean value based on whether an object equal to the parameter ‘item’ is contained within the List.
Insert(int index, T item) – Inserts the parameter ‘item’ in to the List at the index specified by the parameter of the same name.
Remove(T item) – Removes an object equal to the parameter ‘item’ from the List. Variations include RemoveAt(int index) which removes an object at the specified index, and RemoveRange(int index, int count) which removes a total of ‘count’ variables starting at ‘index’.
ToArray() – Returns a normal one-dimensional array, containing all of the elements in the list.
These are not the only methods in the List class. Amongst others there are a number of ‘Find...’ methods and a ‘Sort’ method that all takes delegate methods as parameters. However they are a little beyond the scope of this intro tutorial.
As you can probably see, the List class provides a lot of functionality and one last thing worth mentioning – objects in a List can be accessed by adding square brackets containing the required index after the name of the List object, just as with an array.
Time to look at some other collections!
The ‘Queue’ Collection
The Queue is similar to the List, except it acts as the name implies. The first notable difference is the way in which objects are stored and removed from the Queue; Queues use a First-In-First-Out way of providing elements. To add an item to the back of the queue we use the ‘Enqueue’ method. To remove and retrieve an element from the front of a Queue we use the ‘Dequeue’ method:
[FONT="]queue.Enqueue([COLOR=#A31515]"Hi there!"[/COLOR]);[/FONT] [FONT="] queue.Enqueue([COLOR=#A31515]"How you doing?"[/COLOR]);[/FONT] [FONT="] queue.Enqueue([COLOR=#A31515]"See you later!"[/COLOR]);[/FONT] [FONT="] [/FONT] [FONT="] [/FONT] [FONT="] [COLOR=#2B91AF]Console[/COLOR].WriteLine(queue.Dequeue()); [COLOR=green]//Hi there![/COLOR][/FONT] [FONT="] [COLOR=#2B91AF]Console[/COLOR].WriteLine(queue.Dequeue()); [COLOR=green]//How you doing?[/COLOR][/FONT] [FONT="] [COLOR=#2B91AF]Console[/COLOR].WriteLine(queue.Dequeue()); [COLOR=green]//See you later![/COLOR][/FONT]
As you can see the oldest item comes out first.
Of the methods shown in the List class, queue only has the Contains, Clear, and ToArray methods. The Queue class does have one additional method that is useful however:
Peek – Returns the front item in the queue, without removing it from the queue.
Although this sort of contradicts the point of a queue it is sometimes necessary to use. Additionally the Queue method also has a TrimExcess function as it expands its space much in the same way as List objects do.
The Queue can seem like quite an obscure idea but it does have useful applications, for example, in a system processing message queues, or checking the state of entities in games.
The ‘Dictionary’ Collection
The Dictionary collection, like the others, is suitably named, this time instead of taking one type parameter in the angle brackets, it takes two; a key, and a value – think of it like a word and a definition.
The Dictionary class has an ‘Add’ method like the ‘List’ class, except that it takes two parameters, one for the key type and one for the value type, and then stores them alongside each other. It also has a ‘Remove’ method that takes a key as a parameter and removes the given key and its associated value.
To access the values in a dictionary we use square brackets like when accessing an array, except we put in a key rather than an integer. For a clearer view, observe this example:
[COLOR=#2B91AF][FONT="] Dictionary[/FONT][/COLOR][FONT="]<[COLOR=blue]string[/COLOR], [COLOR=blue]double[/COLOR]> values = [COLOR=blue]new[/COLOR] [COLOR=#2B91AF]Dictionary[/COLOR]<[COLOR=blue]string[/COLOR],[COLOR=blue]double[/COLOR]>();[/FONT] [FONT="] values.Add([COLOR=#A31515]"pi"[/COLOR], 3.14);[/FONT] [FONT="] values.Add([COLOR=#A31515]"euler"[/COLOR], 2.71);[/FONT] [FONT="] values.Add([COLOR=#A31515]"cm-per-inch"[/COLOR], 2.54);[/FONT] [FONT="] [/FONT] [FONT="] [COLOR=blue]double[/COLOR] blah = values[[COLOR=#A31515]"pi"[/COLOR]] * values[[COLOR=#A31515]"euler"[/COLOR]]; [COLOR=green]//3.14 * 2.71[/COLOR][/FONT]
And that’s all there is for this introduction! Enjoy.
Edited by Roger, 17 March 2011 - 09:18 PM.


Sign In
Create Account


Back to top









