Tom Gullen
Tom Gullen

Reputation: 61725

C# LinkedList<> remove by index

Given a:

LinkedList<int> myList;

How would I remove an element at index n? I can't seem to find any methods, only ones to remove by value which is no good as this particular list can have duplicate values.

EG:

myList.removeAt(n);

Upvotes: 1

Views: 3724

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

Linked lists have great advantage in speed if you are adding or removing a node you have a existing reference to, but when you don't have a reference the best you can do is walk the list to the index, grab the node, then delete it.

Here is a extension method that does that process. It returns a reference to the removed node in case you want it later to insert to some other list or you are moving it's position within the list.

public static class ExtensionMethods
{
    public static LinkedListNode<T> RemoveAt<T>(this LinkedList<T> list, int index)
    {
        LinkedListNode<T> currentNode = list.First;
        for (int i = 0; i <= index && currentNode != null; i++)
        {
            if (i != index)
            {
                currentNode = currentNode.Next;
                continue;
            }

            list.Remove(currentNode);
            return currentNode;
        }

        throw new IndexOutOfRangeException();
    }
}

Upvotes: 1

Related Questions