Reputation: 29178
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
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
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