Yes, you cannot iterate over a collection and modify it at the same time. However, LinkedList<T> makes iterating explicitly pretty easy:
public void DeleteNode(int x, LinkedList<name> myLinkedList) { var node = myLinkedList.First; while (node != null) { var nextNode = node.Next; if (node.Value.num == x) { myLinkedList.Remove(node); } node = nextNode; } }
Note that you cannot leave just by taking node = node.Next; as the last line; node is invalid when deleting it.
This approach allows a single crawl of the list in O (n) and is probably the most efficient approach you will find. It does not require copying or working with a collection (say List<T> ) with less efficient removal complexity.
source share