Linked List in C#
Author: haytac
Creation Date: 5/15/2012 7:38 PM
profile picture

haytac

#1
Hi, I am not sure if this issue shows up in WL C# or generic C#. I posed the question to Microsoft forums as well.
- I have a LinkedList<T> where T (element) is a structure defined as a public class.
- Certain events over time are captured and stored in each element which is then added to the linked list
- I can see that the list grows as the .Count member increases over time, also at each step during program execution when a new element is added, I can see (PrintDebug) that .Last has the correct member values.
- When I do LinkedListNode<T> = LinkedList<T>.Last followed by:
- LinkedListNode<T> = LinkedListNode<T>.Previous followed by:
- T = LinkedListNode<T>.Value
- I see that a component of the T element has the value of the last added node rather than the node before. This is my problem

Here is how the LinkedList is defined:
LinkedList<Element> LinkedListOfElements = new LinkedList<Element>();

Thanks and Regards
profile picture

haytac

#2
Hi Again,

Here is the code. I find that .First and .Last both yield answers expected from .Last.

This was compiled in Visual Studio 2010 so is independent of the WL environment.

Thanks and Regards,
Hal

CODE:
Please log in to see this code.
profile picture

Eugene

#3
Just wanted to know if there's a problem using any other .NET collection?
profile picture

haytac

#4
Hi Eugene,

The answer from Microsoft forums came to be:
- Use LLElement = new LinkedListElement(); after each AddLast statement
- To create a new memory location to be attached to the linked list each time
- Otherwise the same memory location gets attached each time and the last value written to it is what gets referenced from each location in the linked list.

I can probably do this with arrays but it will be more cumbersome.

Thanks and Regards,
profile picture

Cone

#5
This is a typical mistake when wanting to store objects in lists. If you need discrete objects in a list and not just a bunch of references to the same one, you need to instantiate a 'new' one before adding it to the list.
This website uses cookies to improve your experience. We'll assume you're ok with that, but you can opt-out if you wish (Read more).