开发者

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

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 performancew开发者_Python百科ise 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.


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜