How can you reverse traverse through a C# collection?

≯℡__Kan透↙ 提交于 2020-01-14 07:13:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!