Introduction
A foreach loop helps you go through each item in a group one by one without worrying about counting or indexes.
A foreach loop helps you go through each item in a group one by one without worrying about counting or indexes.
foreach (var item in collection)
{
// use item here
}item is each element you get from the collection one by one.string[] fruits = {"apple", "banana", "cherry"};
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}List<int> numbers = new List<int> {1, 2, 3}; foreach (int number in numbers) { Console.WriteLine(number * 2); }
This program creates a list of colors and prints each color with a label using a foreach loop.
using System; using System.Collections.Generic; class Program { static void Main() { List<string> colors = new List<string> {"red", "green", "blue"}; foreach (var color in colors) { Console.WriteLine($"Color: {color}"); } } }
Foreach loops are safer and easier than for loops when you just want to read items.
You cannot add or remove items from the collection while inside a foreach loop.
Foreach works with any collection that implements IEnumerable.
Foreach loops let you visit each item in a collection easily.
They avoid mistakes from counting indexes manually.
Use foreach when you want to read or process all items one by one.
foreach loop do in C#?foreach loop over a list of strings named names?string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
Console.Write(fruit + " ");
}List<int> numbers = new List<int> {1, 2, 3};
foreach (int num in numbers)
{
numbers.Remove(num);
}Dictionary<string, int> scores, how can you use a foreach loop to print all keys with values greater than 50?Pass the test and this pattern moves unknown