Is it possible to have a foreach statement that will traverse through a Collections object in reverse order?
If not a foreach statement is there any other way? Thanks.
Is it possible to have a foreach statement that will traverse through a Collections object in reverse order?
If not a foreach statement is there any other way? Thanks.
You can use a normal for
loop backwards, like this:
for (int i = collection.Count - 1; i >= 0 ; i--) {
var current = collection[i];
//Do things
}
You can also use LINQ:
foreach(var current in collection.Reverse()) {
//Do things
}
However, the normal for
loop will probably be a little bit faster.
If you're using 3.5, looks like there is a Reverse() method in LINQ That won't iterate through in reverse order, but would reverse the entire list, then you could do your foreach.
Or you could use a simple for statement:
for(int i = list.Count -1; i >= 0; --i)
{
x = list[i];
}
You could just call Reverse() on the collection.
foreach(var item in collection.Reverse()) { ... }
Alternatively, if the collection's an IEnumerable and therefore without random access, use System.Linq's IEnumerable.Reverse() method and apply forearch as usual.
using System.Linq;
foreach (var c in collection.Reverse()) {
}
List<string> items = new List<string>
{
"item 1",
"item 2",
"item 3",
"item 4",
};
lines.AsEnumerable().Reverse()
.Do(a => Console.WriteLine(a), ex => Console.WriteLine(ex.Message), () => Console.WriteLine("Completed"))
.Run();