Files
freeCodeCamp/guide/english/csharp/foreach/index.md

35 lines
1.1 KiB
Markdown
Raw Normal View History

2018-10-12 15:37:13 -04:00
---
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.
2018-10-12 15:37:13 -04:00
### Example
```csharp
// syntax
2018-10-12 15:37:13 -04:00
foreach (element in iterable-item)
{
// body of foreach loop
}
// sample code
2018-10-12 15:37:13 -04:00
List<string> Names = new List<string>{ "Jim", "Jane", "Jack" }
foreach(string name in Names)
{
Console.WriteLine("We have " + name);
}
```
### Output:
```sh
> We have Jim
> We have Jane
> We have Jack
```