C #: Why does LinkedList not have a RemoveAll method that uses a predicate?

I have LinkedList nodes, each of which stores LinkedList edges. I wanted to do something line by line

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

But without RemoveAll, this happens. I don’t understand why he doesn’t have it, as other collections do. This would have to go through all the elements and delete only one of what I understand would not be bad performance 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; } 

As long as it works, it makes things more complex than what they are.

+6
collections c #
source share
1 answer

I can not say why this method does not exist. This would seem to be a useful method. You can add it yourself using the extension method. Here's my (probably bad, and untested) attempt to do this:

 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 it works:

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

Alternatively, you can invert the criterion for selecting the elements you want to keep and make a new LinkedList from them:

 nodes = new LinkedList<MyNode>(nodes.Where(n => n.edges.Count != 0)); 
+8
source share

All Articles