Files
freeCodeCamp/guide/english/csharp/foreach/index.md
Randell Dawson 0a1eeea424 fix(guide) Replace invalid prism code block names (#35961)
* fix: replace sh with shell

fix replace terminal with shell

fix replace node with js

fix replace output with shell

fix replace cs with csharp

fix replace c++ with cpp

fix replace c# with csharp

fix replace javasctipt with js

fix replace syntax  with js

fix replace unix with shell

fix replace linux with shell

fix replace java 8 with java

fix replace swift4 with swift

fix replace react.js with jsx

fix replace javascriot with js

fix replace javacsript with js

fix replace c++ -  with cpp

fix: corrected various typos

fix: replace Algorithm with nothing

fix: replace xaml with xml

fix: replace solidity with nothing

fix: replace c++ with cpp

fix: replace txt with shell

fix: replace code with json and css

fix: replace console with shell
2019-05-15 19:08:19 +02:00

35 lines
1.1 KiB
Markdown

---
title: Foreach Loop
---
## Foreach Loop
The `foreach` loop executes a block of code for each item in a collection. The benefit of the `foreach` loop is you need not know how many items are within the collection to iterate through it; you simply tell your `foreach` loop to loop through the collection, as long as there are items within it. It is useful for iterating through lists, arrays, datatables, IEnumerables and other list-like data structures. It can be less efficient than a very well designed `for` loop, but the difference is negligible in most cases.
It is worth noting however, that when a `foreach` loop iterates through a data structure, each variable is read-only. Ideally, when you want to modify data in a loop, a `for` loop is the better choice.
### Example
```csharp
// syntax
foreach (element in iterable-item)
{
// body of foreach loop
}
// sample code
List<string> Names = new List<string>{ "Jim", "Jane", "Jack" };
foreach(string name in Names)
{
Console.WriteLine("We have " + name);
}
```
### Output:
```shell
> We have Jim
> We have Jane
> We have Jack
```