Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Why doesn't LinkedList have a RemoveAll method that takes a predicate?

Tags:

c#

collections

I have a LinkedList of nodes each storing a LinkedList of edges. I wanted to do something along the lines of

nodes.RemoveAll(n => n.edges.Count == 0)

But without RemoveAll there goes that. I don't understand why it doesn't have it, since other collections do. This would have to iterate through all elements too and remove only one at a time from what I understand, which wouldn't be bad performancewise for a linked list.

Now I have to do this instead:

for (LinkedListNode<MyNode> n2 = nodes.First; n2 != null; )
{
    LinkedListNode<MyNode> temp = n2.Next;
    if (n2.Value.edges.Count == 0)
        nodes.Remove(n2);
    n2 = temp;
}

While it works, it makes things seem more complicated than what they are.

like image 546
zxcvbnm Avatar asked Feb 03 '23 06:02

zxcvbnm


1 Answers

I can't say why that method doesn't exist. It would seem a useful method to have. You could add it yourself using an extension method. Here's my (probably bad, and not tested) attempt at doing that:

public static class LinkedListExtensions
{
    public static void RemoveAll<T>(this LinkedList<T> linkedList,
                                    Func<T, bool> predicate)
    {
        for (LinkedListNode<T> node = linkedList.First; node != null; )
        {
            LinkedListNode<T> next = node.Next;
            if (predicate(node.Value))
                linkedList.Remove(node);
            node = next;
        }
    }
}

Then this works:

nodes.RemoveAll(n => n.edges.Count == 0);

Alternatively you could invert the criterion to select the elements you want to keep and make a new LinkedList from them:

nodes = new LinkedList<MyNode>(nodes.Where(n => n.edges.Count != 0));
like image 72
Mark Byers Avatar answered Feb 05 '23 21:02

Mark Byers