hello hello - 2 months ago 7
C# Question

convert for loop to foreach with index

I have this

ToString
method used to write out objects. I'm trying to convert the
for
loop to a
foreach
loop.
Without using LINQ.

Any pointers will be appreciated.

public override string ToString()
{
StringBuilder output = new StringBuilder();
output.AppendFormat("{0}", count);
for (var index = 0; index < total; index++)
{
output.AppendFormat("{0}{1}{2} ", array[index], array[index].GetInfo,
string.Join(" ", array[index].Content(index)),
);
}
return output.ToString();
}

Answer

Here is a refactoring based on your current code.

public override string ToString() {
    var output = new StringBuilder();
    output.AppendFormat("{0}", count);
    var index = 0;
    foreach (var item in array) {
        if (item!=null) {
            output.AppendFormat("{0}{1}{2} ", item, item.GetInfo,
                              string.Join(" ", item.Content(index++)),
                            );
        }
    }
    return output.ToString();
} 

Using linq you could perform the same with a indexed Select without directly calling the foreach which is used under the hood

public override string ToString() {
    var output = new StringBuilder();
    output.AppendFormat("{0}", count);
    array.Select((item, index) =>
        output.AppendFormat("{0}{1}{2} ", item, item.GetInfo,
                              string.Join(" ", item.Content(index)),
                            )
    );
    return output.ToString();
}