Eric Sjöström Jennerstrand

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

Foreach loop in C# – Simple use

Foreach loop in C# – Simple
Foreach is in my opinion the best way to iterate a List of objects in C# and it’s super logical. On the left side of the declaration you have what is inside the List. And on the right side you have the List.
Like this:

foreach(string value in listOfStrings)

foreach(Book book in listOfBooks)

As you see above, we say: I want to loop the listOfBooks and in every iteration you get the next book in the List to work with. Which means that you can modify the properties of each Book as you iterate the List.

foreach(Book book in listOfBooks)
{
    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 and for loops if 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/for-loop-in-c-sharp-simple.

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

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>