Iterating C# StringBuilder in a foreach loop

The StringBuilder class in C# is used for efficient string manipulation when dealing with multiple string operations. While StringBuilder itself is not directly iterable in a foreach loop, you can use foreach loops to iterate over collections and append elements to a StringBuilder.

Syntax

Following is the syntax for using foreach with StringBuilder

StringBuilder sb = new StringBuilder();
foreach (type item in collection) {
    sb.Append(item);
}

Using foreach to Build StringBuilder from Array

You can iterate through a string array and append each element to a StringBuilder

using System;
using System.Text;

public class Demo {
    public static void Main() {
        // string array
        string[] myStr = { "One", "Two", "Three", "Four" };
        StringBuilder str = new StringBuilder("We will print now...").AppendLine();

        // foreach loop to append elements
        foreach (string item in myStr) {
            str.Append(item).AppendLine();
        }
        Console.WriteLine(str.ToString());
    }
}

The output of the above code is −

We will print now...
One
Two
Three
Four

Using foreach with StringBuilder and Lists

You can also iterate through a List and format the output while building the StringBuilder

using System;
using System.Collections.Generic;
using System.Text;

public class Demo {
    public static void Main() {
        List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
        StringBuilder result = new StringBuilder("Numbers: ");

        foreach (int num in numbers) {
            result.Append(num).Append(" ");
        }
        
        Console.WriteLine(result.ToString());
    }
}

The output of the above code is −

Numbers: 10 20 30 40 50 

Using foreach to Build Formatted Output

Here's an example that demonstrates building formatted output using foreach with conditional logic −

using System;
using System.Text;

public class Demo {
    public static void Main() {
        string[] fruits = { "Apple", "Banana", "Orange", "Grape" };
        StringBuilder menu = new StringBuilder("Fruit Menu:").AppendLine();

        int index = 1;
        foreach (string fruit in fruits) {
            menu.Append(index).Append(". ").Append(fruit).AppendLine();
            index++;
        }
        
        Console.WriteLine(menu.ToString());
    }
}

The output of the above code is −

Fruit Menu:
1. Apple
2. Banana
3. Orange
4. Grape

Key Benefits

  • Performance: StringBuilder is more efficient than string concatenation for multiple operations.

  • Flexibility: You can apply conditional logic while building strings in the foreach loop.

  • Method Chaining: StringBuilder methods return the same instance, allowing for method chaining.

Conclusion

While StringBuilder itself cannot be iterated directly in a foreach loop, you can effectively use foreach loops to iterate over collections and build strings using StringBuilder. This approach provides better performance than regular string concatenation when dealing with multiple string operations.

Updated on: 2026-03-17T07:04:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements