Foreach C#

A program iterates over a collection. The index of each element is not needed. Only the elements are needed. With foreach we access just the elements.

A foreach-loop, this is the easiest, least error-prone loop. It is preferred in many program contexts. Here are some samples:

using System;
class Program
{
static void Main()
{
string[] pets = { “dog”, “cat”, “bird” };
// … Loop with the foreach keyword.
foreach (string value in pets)
{
Console.WriteLine(value);
}
}
}
Output
dog
cat
bird

– – – – – – – –

using System;
using System.Collections.Generic;
class Program
{
static Dictionary<int, int> _f = new Dictionary<int, int>();
static void Main()
{
// Add items to dictionary.
_f.Add(1, 2);
_f.Add(2, 3);
_f.Add(3, 4);
// Use var in foreach loop.
foreach (var pair in _f)
{
Console.WriteLine(“{0},{1}”, pair.Key, pair.Value);
}
}
}