问题
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 another way?
回答1:
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.
回答2:
You could just call Reverse() on the collection.
foreach(var item in collection.Reverse()) { ... }
回答3:
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];
}
回答4:
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()) {
}
回答5:
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();
Reactive Extension for .NET 3.5/4.0
来源:https://stackoverflow.com/questions/3056155/how-can-you-reverse-traverse-through-a-c-sharp-collection