Eric Sjöström Jennerstrand

Litium E-commerce, C#, .NET MAUI, Javascript, React, Azure, Git. .NET, Node and more!
C Sharp

Reverse FOR loop in C# – A quick look

for (int i = list.Count - 1; i >= 0; i--)
{
    list[i] = 1337;
}

The reverse FOR loop in C# are useful if you need to iterate a List or array backwards. Without first having to reversing it, which can be time and memory consuming.
Therefore, by using a reversed FOR loop you can traverse a list, array or string backwards in a simple way.

So if you take a look at the examples you can see 2 versions of the reverse FOR loop in C#. Firstly, the classic way and after is a simplified way, by combining the condition and decrement of i.

for (int i = list.Length; i-- > 0;)
{
    list[i] = 1337;
}
Evolving, just backwards - PewDiePie - Reverse FOR loop in C#

The for statement executes a statement or a block of statements while a specified Boolean expression evaluates to true.

At any point within the for statement block, you can break out of the loop by using the break statement, or step to the next iteration in the loop by using the continue statement. You can also exit a for loop by the gotoreturn, or throw statements.

So why don’t you checkout these simple easy to read articles about adding objects in list, for loops and reverse for loops if you want som extra reading:
https://www.jennerstrand.se/add-object-to-list-in-c-sharp.
https://www.jennerstrand.se/for-loop-in-c-sharp-simple.
https://www.jennerstrand.se/reverse-for-loop-in-c-sharp.

Add object to List in C# – simple and the links above. Is part of a series of easy read and quick use code examples. That you can use in your c#/.net coding!

3 thoughts on “Reverse FOR loop in C# – A quick look

  • How to create a directory in C# - Eric Jennerstrand
    2021-08-15 at 16:05

    […] out these simple easy to read articles about add object to List, reverse for loops and for loops if you want som extra […]

  • How to create a file in C# - Eric Jennerstrand
    2021-08-15 at 16:27

    […] out these simple easy to read articles about add object to List, reverse for loops and for loops if you want som extra […]

  • Howdy!
    2022-01-26 at 23:05

    Howdy! I just would like to give you a huge thumbs up for your excellent info you have got here on this post.
    I’ll be coming back to your site for more soon.

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>