✨ Shield now has support for Avalonia UI

C# Foreach Loop Guide (From A to Z)

May 15, 2023 | .NET, C#


Introduction to C# Foreach Loop

In this brave new world of C# programming, we developers are constantly looking for ways to write efficient, clean, and flexible code. One such tool at our disposal is the good old foreach loop in C#. Buckle up, because we’re about to dive into the realm of foreach loops, exploring everything from the basics to advanced techniques that’ll make your code shine!

What is Foreach Loop in C#?

foreach is a powerful loop construct used primarily for iterating through collections like arrays, lists, and other data structures in C#. With foreach, you can quickly loop through elements in a collection without needing to worry about the length or the index of the elements.

Advantages of Using C# Foreach Loop

  • Easy to read and understand
  • No need to know the length of the collection in advance
  • No need to keep track of the index during iteration
  • Can be applied to various data structures with minimal code changes

C# Foreach Loop Syntax and Basic Usage

Time for a quick introduction to the basic syntax and usage of C# foreach loops, so that you have a solid foundation to build upon when we venture into more complex topics.

Understanding Foreach C# Syntax

The general syntax for a C# foreach loop looks like this:

foreach (type variableName in collection)
    // Code to be executed for each element
  • type: The data type of the elements in the collection
  • variableName: A temporary variable to hold the reference to the current element in the loop
  • collection: The collection or data structure you want to iterate through

Implementing a Basic C# Foreach Loop

string[] fruits = new string[] { "apple", "banana", "cherry" };

// Simple foreach loop using the basic syntax
foreach (string fruit in fruits)

The code above shows a simple example of iterating through an array of strings using the foreach loop in C#. The output would be:


Diving Deeper into C# Foreach

In this section, we’ll dig deeper into various scenarios and advanced techniques for C# foreach loops so that you can harness its full power.

C# Foreach in Arrays

Let’s go beyond the basics and explore how foreach can seamlessly work with arrays in C#.

C# Foreach in Array: The Basics

Suppose we have an array of integers and we want to print each element. We can easily do that using a foreach loop:

int[] numbers = new int[] { 1, 2, 3, 4, 5 };

foreach (int num in numbers)

This code will print the numbers 1 through 5, with each number on a new line.

Advanced Array.Foreach Techniques in C#

Wait a minute… there’s more! The Array class provides the Array.ForEach method, which is an advanced version of the standard foreach loop, especially handy when you’re working with arrays. Let’s see an example:

string[] greetings = new string[] { "Hello", "Hola", "Bonjour" };

// Using Array.ForEach with a delegate (pre-C# 7.x)
Array.ForEach(greetings, delegate(string greeting)

// Using Array.ForEach with a lambda expression (C# 7.x and later)
Array.ForEach(greetings, greeting => Console.WriteLine(greeting));

Both examples above will produce the same output as the previous example, but the very mention of “delegate” and “lambda expression” means we’ve entered the realm of seriously cool C# stuff, eh?

C# List Foreach: Traversing Collections with Ease

Basic C# Foreach Loop for Lists

Lists are a widely used data structure in C#, and foreach loops excel in gracefully iterating through them. Behold:

List<string> cities = new List<string> { "New York", "Los Angeles", "Chicago" };

foreach (string city in cities)

The output will be the list of city names, each printed on a new line.

Enhancing the Foreach Experience with C# List.Foreach

You’re not limited to just basic in C# foreach, my programming friend! The List<T> class provides the List<T>.ForEach method, which allows you to supply an Action<T> delegate (no need to panic; this just means you can use a lambda expression) to execute for each element in the list. Time for an example:

List<string> foods = new List<string> { "Pizza", "Burger", "Sushi" };

// Using List<T>.ForEach with a lambda expression
foods.ForEach(food => Console.WriteLine(food));

And there you have it—your food list has been neatly printed, with each item on a new line, using the List<T>.ForEach method.

Handling Objects in C# Foreach Loops

Let’s amp it up even more by working with custom objects in C# foreach loops.

Iterating Through Custom Objects in Foreach Loop C#

Say you have a custom class Person:

class Person
    public string Name { get; set; }
    public int Age { get; set; }

List<Person> persons = new List<Person>
    new Person { Name = "John", Age = 33 },
    new Person { Name = "Jane", Age = 29 },
    new Person { Name = "Steve", Age = 42 }

Can you still use foreach? You bet! Just check this out:

foreach (Person person in persons)
    Console.WriteLine($"{person.Name} is {person.Age} years old.");

The output will display each person’s name and age, formatted nicely on a new line.

C# For Each with Collection Initialization

You can also initialize and fill a collection directly inside the foreach loop iteration. How? Let’s say you want to create a list of numbers that are squares of the original numbers list:

List<int> numbers = new List<int> { 2, 3, 4, 5 };
List<int> squares = new List<int>(); // An empty list to store the squares

foreach (int num in numbers)
    squares.Add(num * num);

// Will print "4 9 16 25"
squares.ForEach(square => Console.Write($"{square} "));

Voilà! We now have a new list of squared numbers.

Advanced C# Foreach Techniques

But wait, there’s more! Let’s explore some nifty tricks and advanced techniques to make your C# foreach loops even more powerful.

The C# .Foreach Extension: Adding Flexibility to C# Foreach Loop

Benefits of Using C# .Foreach Extension

With the aptly named .Foreach extension method, you can customize the foreach loop behavior to make it more flexible and clean when working with enumerable collections, especially custom ones. So, what’s the catch? It’s not in the standard .NET library, so you’ll need to create it yourself. But that’s no big deal for a C# wizard like yourself, right?

Implementing Custom .Foreach Extensions

public static class EnumerableExtensions
    public static void Foreach<T>(this IEnumerable<T> source, Action<T> action)
        foreach (T item in source)

Well, would you look at that? It’s an extension method that enables you to use the cool .Foreach() syntax with your collections! Here’s an example of how it works in action:

List<string> animals = new List<string> { "Dog", "Cat", "Rabbit" };

// Using the custom .Foreach extension
animals.Foreach(animal => Console.WriteLine(animal));

Theming C# Foreach with LINQ

LINQ, which stands for Language Integrated Query, is a fantastic (and might I add, magical) C# feature that enables you to seamlessly query and manipulate data in creative ways—especially when combined with foreach.

How LINQ Complements the C# Foreach Loop

LINQ empowers you to execute many complex operations—like filtering, sorting, and transforming data—right within the foreach loop itself, making your code more clean and elegant.

Basic LINQ Usage in C# With Foreach Loop

Time for an example, say you want to iterate through a list of numbers, but you only want to print the even ones:

List<int> nums = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Using LINQ with a foreach loop
foreach (int evenNum in nums.Where(num => num % 2 == 0))

Behold! The power of LINQ has come to your C# foreach loop’s rescue, and your loop output will only show the even numbers (2, 4, 6, and 8).

Return in Foreach C#: Exiting Early and Gracefully

Time to face the inevitable—sometimes, a loop must come to an end before completing its iterations. Do not despair, my C# compadres, because there are ways to break and return with style.

Breaking Out of a C# Foreach Loop

The break statement can be your savior, as it allows you to exit the loop prematurely:

int[] luckyNumbers = new int[] { 7, 5, 12, 5, 6, 7 };

foreach (int num in luckyNumbers)
    if (num == 5)
        break; // This will exit the loop when it encounters the first 5
    Console.Write($"{num} ");

This code would output “7”, since the loop would terminate when encountering the first “5”.

Returning Data from C# Foreach Loop

List<int> ages = new List<int> { 29, 32, 35, 40, 45 };

string FindAgeCategory(int age)
    foreach (int milestone in ages)
        if (age < milestone)
            return $"Under {milestone}";
    return "Not an age category";

Console.WriteLine(FindAgeCategory(34)); // Output: "Under 35"

In this example, the FindAgeCategory function returns an age category based on a given age by iterating through a list of age milestones using a foreach loop.

Enhancing Iteration with Enhanced For Loop C# Alternatives

There’s more than one way to skin a cat—or, in this case, loop through data in C#. Let’s take a peek at some alternatives that go beyond the foreach.

C# Each: Making Iteration More Intuitive

The Each method is not available in the C# standard library, but we can craft it ourselves using an extension method that offers a more intuitive syntax.

Syntax of C# Each

public static class EnumerableExtensions
    public static void Each<T>(this IEnumerable<T> source, Action<T> action)
        foreach (T item in source)

Once the Each extension is created, it can be easily used like this:

List<string> colors = new List<string> { "Red", "Green", "Blue" };

// Using the custom Each extension
colors.Each(color => Console.WriteLine(color));

Feel the power! With your new custom Each method, you can loop through collections in a more expressive manner.

C# For Each Loop Variants for Different Data Structures

Sometimes, other data structures will lure you away from your beloved arrays and lists. Fear not, for foreach has got your back! Behold:

C# Foreach Loop with Dictionaries

Dictionary<string, string> capitals = new Dictionary<string, string>
    { "France", "Paris" },
    { "United States", "Washington D.C." },
    { "Germany", "Berlin" }

foreach (KeyValuePair<string, string> entry in capitals)
    Console.WriteLine($"{entry.Key}'s capital is {entry.Value}");

This output displays each country and its corresponding capital.

Iterating Through Sets in C#

HashSet<string> programmingLanguages = new HashSet<string> { "C#", "Java", "Python", "JavaScript" };

foreach (string language in programmingLanguages)

See? You just iterated through a HashSet of programming languages. Impressive, isn’t it?

Exploring foreach in Array C# and Other Data Structures

Sometimes, your data structures may have a couple of extra dimensions to them. But don’t fret, the C# foreach loop can handle just about anything you throw at it!

C# Array Foreach: Looping Through Multidimensional Arrays

int[,] matrix = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };

foreach (int element in matrix)
    Console.Write($"{element} ");

// Output: "1 2 3 4 5 6"

As you can see, the foreach loop gracefully iterates through a multidimensional array.

Foreach in Nested Lists and Arrays

Nested loops? No problem! C# foreach can handle them with ease:

List<List<int>> nestedList = new List<List<int>>
    new List<int> { 1, 2, 3 },
    new List<int> { 4, 5, 6 },
    new List<int> { 7, 8, 9 }

foreach (List<int> innerList in nestedList)
    foreach (int num in innerList)
        Console.Write($"{num} ");

// Output:
// 1 2 3
// 4 5 6
// 7 8 9

Nested loops are a piece of cake for the mighty foreach.

C# Foreach with Tuples and ValueTuples

Ready to be amazed? Even when dealing with the mystic power of tuples and value tuples, the confidence-inducing foreach stands strong.

List<(string, int)> students = new List<(string, int)>
    ("Alice", 25),
    ("Bob", 22),
    ("Charlie", 28)

foreach ((string name, int age) in students)
    Console.WriteLine($"{name} is {age} years old");

// Output:
// Alice is 25 years old
// Bob is 22 years old
// Charlie is 28 years old

With the awe-inspiring might of C# foreach combined with tuples, you have the power to fully express your code’s intentions.

C# Foreach Loop Best Practices and Optimization Tips

Now that you have conquered the C# foreach loop, it’s time to optimize and harness its full potential. Here are some tips and best practices to ensure your code stays clean, efficient, and elegant:

Write Efficient Foreach Loops

Keeping your foreach loop body concise and focused on a single task can improve the readability and maintainability of your code. Moreover, it enables you to quickly identify and optimize the performance-critical sections of your code.

For example, instead of writing a foreach loop that performs multiple operations, like filtering, transformation, and aggregation, consider splitting these tasks into separate loops or leveraging the power of LINQ to achieve the desired result.

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

// Bad example: Multiple operations within a single foreach loop
int sumOfEvenNumbers = 0;
List<int> oddNumbers = new List<int>();
foreach (int num in numbers)
    if (num % 2 == 0)
        sumOfEvenNumbers += num;

// Better example: Separate loops for each operation
int sum = numbers.Where(n => n % 2 == 0).Sum();
List<int> odds = numbers.Where(n => n % 2 != 0).ToList();

In the better example, we’ve utilized LINQ to separate our two tasks, making it easier to understand and maintain.

Error Handling in Foreach Loop

Using try and catch blocks within your foreach loop allows you to handle exceptions and errors gracefully, ensuring that your code remains robust and fault-tolerant. Proper error handling can also help to identify potential issues and improve the debugging experience when working with your code.

Here’s an example of how you can handle exceptions within a foreach loop:

List<string> urls = new List<string> { "http://example.com", "this is not a URL", "https://www.bytehide.com" };

foreach (string url in urls)
        var webClient = new WebClient();
        string content = webClient.DownloadString(url);
        Console.WriteLine($"Successfully downloaded content from {url}");
    catch (Exception ex)
        Console.WriteLine($"Error while downloading content from {url}: {ex.Message}");

In this example, we download the content from a list of URLs using a WebClient. If an exception occurs while downloading the content (e.g., an invalid URL), it will be caught, and an appropriate error message will be displayed.

When to Use C# Foreach Loop and When to Choose Alternatives

There are cases when you might want to use alternatives to foreach loops for better performance, readability, or flexibility:

  • Use the conventional for loop when dealing with multidimensional arrays or when you need to keep track of the index of the current element.
  • Use the while loop when the number of iterations depends on a particular condition and must be determined dynamically.
  • Leverage the power of LINQ for situations where you want to filter, transform, or aggregate data.

For example, if you want to calculate the sum of all the values in a two-dimensional array, the for loop would be more appropriate than a foreach loop:

int[,] matrix = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
int total = 0;

for (int row = 0; row < matrix.GetLength(0); row++)
    for (int col = 0; col < matrix.GetLength(1); col++)
        total += matrix[row, col];

Console.WriteLine($"Total sum: {total}");

In this example, the for loop enables us to iterate through each row and column in the 2D array effortlessly and maintain precise control over the indices.

By following these best practices and optimization tips, you can further enhance the power of C# foreach loops, making your code cleaner, more efficient, and easier to maintain.

Closing in on an epic ride through C# foreach loops, we’ve explored everything from basic syntax and usage to advanced techniques and nifty tricks. With this newfound knowledge, go forth and conquer the syntax, semantics, and style of the amazing C# foreach loop!

You May Also Like