foreach loop in C#

By   Calendar icon Apr 10, 2019   Level 1 icon

Description:

In this article, we explain how the foreach statement in the C# language works and we give several examples.

Preferencesoft

Image by aatlas from Pixabay

foreach loop

foreach is a loop statement that repeats a statement or sequence of statements by browsing a list or collection.

It has the following syntax:

foreach (Object obj in collection) statement;

or

foreach (Object obj in collection)
{
   instruction_1;
   // ...
   instruction_n;
}

Example:

using System;
namespace ForEachOverArray
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        int[] ar = new int[] {1, 5, 9, 13, 17, 21} ;
        foreach (int i in ar)
            System.Console.WriteLine(i);
        System.Console.ReadKey();
    }
}
}

Example:

using System;
namespace InString
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        string str = "0123456789";
        foreach (char c in str)
            System.Console.WriteLine(c);
        System.Console.ReadKey();
    }
}
}

Output

0
1
2
3
4
5
6
7
8
9

Example:

using System;
using System.Collections.Generic;
namespace InList
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        List<string> list = new List<string> {"abcd", "bcde", "cdef", "defg"} ;
        foreach (string s in list)
            System.Console.WriteLine(s);
        System.Console.ReadKey();
    }
}
}

Output

abcd
bcde
cdef
defg

foreach over IEnumerable

It is possible to declare classes deriving from IEnumerable, to create custom collections for iterating over it by using foreach. In fact, we need to create a class deriving from IEnumerable (with a method GetEnumerator) and a class deriving from IEnumerator (with four methods MoveNext, Current, IEnumerator.Current and Reset).

Example:

Let's write a program that implements an IEnumerator that iterates through an array by alternately considering the 2nd object then the 1st, then the 4th then the 3rd etc. and the last object in case of imparity of the number of elements.

Case of imparity:

odd exchange

Parity case:

even exchange

using System;
using System.Collections.Generic;
using System.Collections;
namespace InList
{

public class Students: IEnumerable
{
    public string[] Names
    {
        get;
        set;
    }
    public IEnumerator GetEnumerator()
    {
        return (IEnumerator) new BiEnumerator(this);
    }
}

public class BiEnumerator: IEnumerator<string>
{
    public BiEnumerator(Students stud)
    {
        _stud=stud;
        _studNumber = _stud.Names.Length;
    }
    private Students _stud;
    private int _studNumber;
    private int _index = -1;
    public void Reset()
    {
        _index=-1;
    }

    public string Current
    {
        get
        {
            if (_index == _studNumber - 1 && _studNumber % 2 == 1)
                return _stud.Names[_index];
            else
                return (_index % 2 == 0 ? _stud.Names[_index+1] : _stud.Names[_index-1]);
        }
    }

    object System.Collections.IEnumerator.Current
    {
        get
        {
            return this.Current;
        }
        //private set;
    }
    public bool MoveNext()
    {
        if (++_index < _studNumber)
        {
            return true;
        }
        else _index = 0;
        return false;
    }
    public void Dispose()
    {
        //throw new Exception("Unsupported Operation");
    }
}

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var students = new Students()
        {
            //Names=new string[]{"hello1", "hello2", "hello3"}
            Names=new string[] {"hello1", "hello2", "hello3", "hello4", "hello5"}
        };
        foreach (string s in students)
        {
            Console.WriteLine(s);
        }
        System.Console.ReadKey();

    }
}
}

Output

hello2
hello1
hello4
hello3
hello5

Empty loop, empty collection

An empty loop is a loop whose instruction block is empty. Like what

using System;
using System.Collections.Generic;

namespace Empty
{

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        foreach (char c in "abc")
        {
        }
        Console.ReadKey();
    }
}
}

Even if c takes each value a, b, c no statement is executed.

In a foreach loop the crossing sequence can be empty. In this case, even if the statement block is not empty, nothing will be executed in the loop.

So, the following statement:

using System;
using System.Collections.Generic;

namespace Empty
{

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        foreach (char c in "")
        {
            Console.WriteLine("ok");
        }
        Console.ReadKey();
    }
}
}

does not display anything.

Nested foreach loops

foreach loops are said to be nested If one of the loops is part of the instruction block of the other loop.

using System;
using System.Collections.Generic;

namespace Empty
{

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        foreach(int i in new int[] {2, 3, 5, 7, 11, 13})
        {
            foreach (char s in "0123456789abcdef".Remove(i))
                Console.Write(" {0} ", s);
            Console.WriteLine();
        }

        Console.ReadKey();
    }
}
}

Output

0 1
0 1 2
0 1 2 3 4
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7 8 9 a
0 1 2 3 4 5 6 7 8 9 a b c

for vs foreach


CSharp

Categories