Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse C# LinkedList in reverse order

Tags:

c#

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)
like image 244
softwarematter Avatar asked Nov 19 '11 11:11

softwarematter


1 Answers

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
}
like image 180
Marc Gravell Avatar answered Oct 04 '22 12:10

Marc Gravell