开发者

How can you reverse traverse through a C# collection?

开发者 https://www.devze.com 2023-01-03 21:58 出处:网络
Is it possible to have a foreach stateme开发者_高级运维nt that will traverse through a Collections object in reverse order?

Is it possible to have a foreach stateme开发者_高级运维nt that will traverse through a Collections object in reverse order?

If not a foreach statement, is there another way?


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.


You could just call Reverse() on the collection.

foreach(var item in collection.Reverse()) { ... }


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];
}


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();           

Reactive Extension for .NET 3.5/4.0

0

精彩评论

暂无评论...
验证码 换一张
取 消