Eric Sjöström Jennerstrand

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

For loop in C# – Simple how to use

For loop in C# – Simple how to use
For is in my opinion one of best way to iterate a List/Array of objects in C#. When you need to keep track on what row in the iteration you are on. There are 3 parts of the For loop declaration, the “counter”, the break expression, and the increment for the counter
Like this:

for(int i = 0; i < 10; i++)
// A variable named i is set to 0.
// The loop will run as long as i is less then 10. (10 times)
// i++ means that every iteration, i will increase by 1.

for(int i = 0; i < listOfBooks.Count; i++)

As you see above, we say: I want to loop the listOfBooks and in every iteration i will be increased by 1. Which means that you have to select the correct object in the list on every iteration. As shown below on line 3.

for(int i = 0; i < listOfBooks.Count; i++)
{
    Book book = listOfBooks[i];

    book.Name = "New Name";
    book.Author = "Jennerstrand";

    if(book.PageNumbers == 100)
    {
        // Do something
    }
}

Checkout these simple easy to read articles about add object to List, reverse for loops an foreach loops f you want som extra reading:
https://www.jennerstrand.se/add-object-to-list-in-c-sharp.
https://www.jennerstrand.se/reverse-for-loop-in-c-sharp.
https://www.jennerstrand.se/foreach-loop-in-c-sharp-simple-use.

For loop in C# – Simple how to use and the links above is part of a series of easy read, quick use examples you can use in your c#/.net coding!

For loop in C#
For loop in C#

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>