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>
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With