smatter
smatter

Reputation: 29178

How to traverse C# LinkedList in reverse order

How can I do the equivalent of the following C++ snippet using C# LinkedList?

std::list<MyClass*>::reverse_iterator itr(it); 
for(; itr != MyList.rend(); ++itr)

Upvotes: 10

Views: 6624

Answers (2)

UnionP
UnionP

Reputation: 1638

An tweak to Marc's while loop is using a for loop, which I find a little cleaner:

for (var el = list.Last; el != null; el = el.Previous)
{
    // use el.Value
}

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062660

As a 1-off, something like:

var el = list.Last;
while (el != null) {
    // use el.Value
    el = el.Previous;
}

If you are doing it regularly, maybe a similar iterator block to yield all the values:

public static IEnumerable<T> Reverse<T>(this LinkedList<T> list) {
    var el = list.Last;
    while (el != null) {
        yield return el.Value;
        el = el.Previous;
    }
}

then:

foreach(var val in list.Reverse()) {
    // use val
}

Upvotes: 19

Related Questions