Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing from a LinkedList

Tags:

c#

linked-list

From the previous question I asked, RemoveAll is the cleanest way to remove from a List<> based on a condition. Curious to know what is the best way to remove from a LinkedList as there is no RemoveAll function there.

List<ItemClass> itemsToErase = new List<ItemClass>();
    foreach(ItemClass itm in DS)
    {
           if(itm.ToBeRemoved)
                itemsToErase .Add(itm);
    }
    foreach(ItemClass eraseItem in itemsToErase)
    {
          DS.Remove(eraseItem );
    }          

EDIT: DS is of type LinkedList<ItemClass>

like image 320
softwarematter Avatar asked Nov 19 '11 16:11

softwarematter


1 Answers

While you can't remove nodes from a LinkedList<T> while iterating it with foreach, you can manually iterate the LinkedList<T> by following the Next property of each LinkedListNode<T>. Just remember the next node of the node before removing it:

var list = new LinkedList<int>(Enumerable.Range(0, 10));
var node = list.First;
while (node != null)
{
    var next = node.Next;
    if (node.Value % 2 == 0)
        list.Remove(node);
    node = next;
}

Extension Method:

public static int RemoveAll<T>(this LinkedList<T> list, Predicate<T> match)
{
    if (list == null)
    {
        throw new ArgumentNullException("list");
    }
    if (match == null)
    {
        throw new ArgumentNullException("match");
    }
    var count = 0;
    var node = list.First;
    while (node != null)
    {
        var next = node.Next;
        if (match(node.Value))
        {
            list.Remove(node);
            count++;
        }
        node = next;
    }
    return count;
}

Usage:

LinkedList<ItemClass> DS = ...
DS.RemoveAll(itm => itm.ToBeRemoved);

See also: Extension Methods (C# Programming Guide)

like image 116
dtb Avatar answered Sep 21 '22 14:09

dtb