foreach
statement provide a simpler way to iterate over a collection of elements. It can be used with types that implement the System.Collections.IEnumerable
or System.Collections.Generic.IEnumerable<T>
interface. Examples of those types include:
- arrays
List<T>
Dictionary<TKey,TValue>
Queue<T>
SortedList<TKey,TValue>
Stack<T> Class
- … etc
The structure of a foreach…in
loop is as follow:
foreach (type name in collection)
{
body
}
where
type
is the type of the elements inside thecollection
,var
keyword can also be used herecollection
is the groups of elements to be iterated
For example, this for loop that print out all the elements in an array
int[] nums = {1, 2, 3, 45, 6, 7, 8, 9};
for (int i = 0; i < nums.Length; i++)
{
Console.WriteLine(nums[i]);
}
can be written using foreach…in
loop
int[] nums = {1, 2, 3, 45, 6, 7, 8, 9};
foreach (int num in nums)
{
Console.WriteLine(num);
}
Live-code example
References
- Docs, M. (2018, June 29). foreach, in (C# reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in‘