foreach
The C# loop that asks a collection for its enumerator and hands you one item at a time.
In more detail
It works with anything that implements IEnumerable<T>, and pulling items is what triggers a deferred LINQ query. await foreach does the same over an IAsyncEnumerable<T>, awaiting between items.
Example
foreach (var qty in orders) Console.Write(qty);Related terms
- enumerator — The object that walks a sequence, with MoveNext to advance and Current to read the item it is on.
- IEnumerable<T> — The .NET interface for any sequence you can loop over one item at a time, the basis of foreach and in-memory LINQ.
- deferred execution — Building a query now but running it only when something asks for its results.
- IAsyncEnumerable<T> — A .NET interface for a sequence whose items arrive over time, consumed with await foreach.
Taught in
- The C# Language: Types, Variables, and Flow Control — Modern .NET Core, C# & Enterprise Microservices
- Collections, Generics, and LINQ — Modern .NET Core, C# & Enterprise Microservices
- Async and Await: Managing Concurrency — Modern .NET Core, C# & Enterprise Microservices