Is this a good way to iterate through a .NET LinkedList and remove items?

I am going to do the following:

for(LinkedListNode<MyClass> it = myCollection.First; it != null; it = it.Next)
{
    if(it.Value.removalCondition == true)
        it.Value = null;
}

I'm curious: just pointing it.Valueto null will really get rid of it.

+5
source share
6 answers

Of course (with a linked list) you need to change the link.

For example, if you want to remove B from LL ABC, you need to change the link from B to C.

I admit that I am not familiar with the implementation of .NET linked lists, but I hope this is the beginning for you.

+1
source

Setting it.Value to null will not remove the node from the list Here is one way:

    for(LinkedListNode<MyClass> it = myCollection.First; it != null; )
    {
        LinkedListNode<MyClass> next = it.Next;
        if(it.Value.removalCondition == true)
              myCollection.Remove(it); // as a side effect it.Next == null

        it = next;
    }
+7
source

, LinkedListNode; , ( node).

A - B - C A - null - C, "" B. , ?

+1

, -

for ( LinkedListNode<MyClass> it = myCollection.First; it != null; it = it.Next ) {
  if ( it.Value.removalCondition == true ) {
    if ( it.Previous != null && it.Next != null ) {
      it.Next.Previous = it.Previous;
      it.Previous.Next = it.Next;
    } else if ( it.Previous != null )
      it.Previous.Next = it.Next;
    } else if ( it.Next != null )
      it.Next.Previous = it.Previous;
    it.Value = null;
  }
}
0

List < > , LinkedList < > , RemoveAll(). :

List<string> list = new List<string>()
{
    "Fred","Joe","John"
};

list.RemoveAll((string val) =>
{
    return (0 == val.CompareTo("Fred"));
});

Linq.

, ToList < > () . . :

LinkedList<string> str = new LinkedList<string>();
str.AddLast("Fred");
str.AddLast("Joe");
str.AddLast("John");

List<string> ls = str.ToList();
ls.RemoveAll((string val) => val.CompareTo("Fred") == 0);
str.Clear();
ls.ForEach((string val) => str.AddLast(val));

, LinkedList :

LinkedList<string> str = new LinkedList<string>();
str.AddLast("Fred");
str.AddLast("Joe");
str.AddLast("John");

LinkedList<string> strCopy = new LinkedList<string>(str);
str.Clear();
foreach (var val in strCopy)
{
    if (0 != val.CompareTo("Fred"))
    {
        str.AddLast(val);
    }
}

, .

0

, , olso null -s, :

for (LinkedListNode<string> node = a.First; node != a.Last.Next; node = node.Next)
{
               // do something here 

}
0
source

All Articles