I have looked around and I can\'t really find an answer I can understand or it doesn\'t apply to me. I have this class:
class Node
{
public int value;
I know this is an old post, but this is what is popping up on google, and I do have a good alternative to the current best answer (not including the desired value condition)
LinkedListNode<ChunkObject> list = new LinkedListNode<ChunkObject>();
for(LinkedListNode<Object> node=list.First; node != null; node=node.Next){
//do stuff
}
This version obviously uses a for loop and moves the variable declaration and increment to one line allowing you to condense and beautify your code.
For this kind of list, you usually keep a reference to the current node (which starts with the head), and after each iteration, you change the value of that reference to the next
node. When currentNode
becomes null
, you have reached the end of the list, as the last element doesn't have a next element.
Something like this:
Node currentNode = head;
while (currentNode != null) {
// do stuff with currentNode.value
currentNode = currentNode.Next;
}
By the way, the BCL already contains some useful classes for this sort of task:
But maybe you need to do it the way you do for some reason :)
Try this basic iteration:
Node tmp = head;
while (tmp != null)
{
//do your checking...
tmp = tmp.next;
}
You iterate through your class as follows:
var currentNode = head;
while ((currentNode != null) && (currentNode.Value != desiredValue))
currentNode = currentNode.next;
When the while
loop completes, currentNode will be null
or contain a node with the desired value.