Today in this section, i am going to talk about Linked Lists. But lets 1st understand Linked Lists here. The purpose of a linked list is to provide a collection where in you can add/remove items very easily. Linked list are having one address section apart from data section as well where in it stores the reference of next node and so on. In case of doubly linked list. on both the ends there are previous and next references of data element, so it can move in the list to and fro.
There are certain features of linked list:-
- Adding/Removing element is fast.
- Good at enumeration
- No index based access to elements.
- Linked Lists are not very good when it comes for memory consumption.
Now, in the below example I have a linked List code. But, one thing to remember here that with Linked List you can’t use collection initializer to set up values. Below in the screen shot i have highlighted the APIs which Linked Lists offer out of the box.
so, if you see the code then i have missed the month march in the collection. Now, lets suppose if i have to add the same in the collection, then how do we do that. So, for doing the same, what we need to do is go ahead and use the API AddAfter on element as shown below in the snippet. Now, one more point to note here that LinkedList
then, this will produce the desired output as shown below.
However, one point to note here this is not the efficient way of using LinkedList although AddAfter() is very efficient because in this case we have used Find() method which will scan the entire list until it finds the desired element. But, in this case i had no choice as i didn’t keep the reference stored upfront.Also, one more important point to note here that if Linked List contains the same value more than once in the list, then Find() will only find the 1st one.
Now, for removing the node you can use Remove(“”), but again this is not very efficient as this is going to scan the List. However, you can also directly use RemoveFirst() or RemoveLast() if your intention to remove the item that one or you can pass the reference of that node likewise. So, this was the Linked List. In the next section, we’ll cover some other collection.