C# Foreach Loop

C# Foreach Loop

The foreach loop in C# is used to iterate over a collection of objects, such as an array, a list, or any other collection that implements the IEnumerable interface. The basic syntax of the foreach loop is:

Syntax:

foreach (type variable in collection)
{
  // code to execute....
}

The foreach loop is a convenient way to iterate over a collection of objects without having to manually manage an index or iterator variable. It also helps to make your code more readable and concise.

In C#, you can use the foreach loop to iterate over elements in an array, a collection, or any other enumerable object.

*** foreach statement iterates over each element in an enumerable object.

*** Both an array and a string are enumerable.

For Example: The following code enumerates over the characters in a string, from the first character through to the last:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (char c in "xdevspace.com")   // c is the iteration variable
                Console.WriteLine(c);
            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Output:

foreach loop in C#

 

1 - Syntax of C# Foreach Loop

foreach (Type var_name in Collection_Object) {

// Statements to Execute

}

If you observe the above syntax, we defined a foreach loop with the collection object and required variable names to access the collection object's elements.

Here, Type is a built-in data-type or custom class type, and var_name is a variable name to access elements from the collection object (Collection_Object) to use it in the foreach loop's body.

 

2 - C# Foreach Loop Flow Chart

Following is the pictorial representation of the foreach loop process flow diagram in the c# programming language.

C# Foreach Loop Flow Chart

 

3 - C# Foreach Loop with Array Example

Following is the example of using a foreach loop in c# programming language to iterate or loop through array elements.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = new string[3] { "Alex", "Bretni", "Foulda" };
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }
            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

If you observe the above example, we created a string array object “names” and looped through each element of the array object using a foreach loop and assigning array elements to string variable “name”.

Output:

When we execute the above c# program, we will get the result below.

 

C# Foreach Loop with Array Example

4 - C# Foreach Loop with List Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "Alex", "Bretni", "Foulda" };
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }
            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

If you observe the above example, we used System.Collections.Generic namespace to access the List object and add string elements to the list. We used foreach to loop through items in the list to print them on the console window.

Output:

When we execute the above c# program, we will get the result below:

C# Foreach Loop with List Example

 

5 - C# Foreach loop in Dictionary

In C#, you can use a foreach loop to iterate over the key-value pairs in a dictionary. The foreach loop will iterate over the keys of the dictionary, and you can use the keys to access the corresponding values.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> colors = new Dictionary<string, int>();
            colors.Add("red", 100);
            colors.Add("blue", 200);
            colors.Add("green", 300);
            foreach (string color in colors.Keys)
            {
                int value = colors[color];
                Console.WriteLine("{0} : value is = {1}", color, value);
            }
            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Output:

C# Foreach loop in Dictionary

In the above example, there is a dictionary called colors that maps strings (colors) to integers (values). Inside the foreach loop, use the Keys property of the dictionary to iterate over the keys of the dictionary, which are the colors. Inside the loop, use the key to access the corresponding value using the square bracket notation, and then print the color and value to the console.

Notice that you're able to iterate over the key-value pairs in the dictionary using a foreach loop by iterating over the keys and then accessing the corresponding values using the keys. If you need to iterate over both the keys and the values, you can use a foreach loop with the KeyValuePair type, like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> colors = new Dictionary<string, int>();
            colors.Add("red", 100);
            colors.Add("blue", 200);
            colors.Add("green", 300);
            foreach (KeyValuePair<string, int> pair in colors)
            {
                string color = pair.Key;
                int value = pair.Value;
                Console.WriteLine("{0} : value is = {1} ", color, value);
            }
            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Output:

C# Foreach loop in Dictionary

In the above example, use a foreach loop with the KeyValuePair type to iterate over the key-value pairs in the colors dictionary. Inside the loop, we use the Key and Value properties of the KeyValuePair object to access the key and value, respectively.