Collection Classes in .net - the LinkedList
This is the eighth part of an article on collection classes in .net with C#. This part covers the LinkedList.
For the first part see http://www.audacs.co.uk/ViewPage.aspx?PageID=512
For the next part on the StringCollection see http://www.audacs.co.uk/ViewPage.aspx?PageID=521
I remember coding Linked Lists in C many many years ago which was lots of fun. The .net framework provides a LinkedList class out of the box in the form of:
System.Collections.Generic.LinkedList<T>
So this is a collection of objects as specified by the T. Each node in the collection is actually a LinkedListNode.
The node item then has a property called Value which is a reference to the actual object.
Each node in the list contains a reference to its preceeding node and the next node. For the first node then the preceeding node reference will be null of course and likewise the last node will have a null reference for its next node. Many .net collections are probably linked lists under the hood I would bet but this one exposes typical linked list methods to us. So its reason for existing is for us to use when we are modelling a problem which behaves like a linked list. This could be something like a GPS route finder application where we have a list of nodes representing points on a map or route.
Lets dive in and have a look at some code:
Ok so first we create an instance of a LinkedList and we call this map.
We then create 5 instances of a MapLocation class which is found at the bottom of the code listing.
We then add the Rugeley object to the map using the AddFirstMethod.
Next we use the AddAfter method to add the rest of the locations. This method takes 2 arguments. The first is a LinkedListNode<T> instance and the second is the MapLocation object to add. The LinkedListNode<T> instance in this case is returned from the Find method and it is this that we are adding after.
We then use a foreach loop to iterate over the List and output the contents to screen.
We then demonstrate a variety of methods and properties such as First, Last, Previous etc. All of these return a LinkedListNode<T> object and that object has a Value property which is a reference to the actual object - in this case the MapLocation. So basically each MapLocation object is wrapped in a LinkedListNode object.
There is of course much more you can do with a LinkedList but this is enough to give you the basic idea and allow you to write some code and do some experimenting.
For the next part on the StringCollection see http://www.audacs.co.uk/ViewPage.aspx?PageID=521