if you want to return a single string with all the data put into it, you are probably looking for something like that:
public string PrintCrate()
{
string rv = "";
foreach (var soda in sodaCans)
{
if (soda != null)
{
rv += "\n" + soda;
}
}
return rv;
}
EDIT: According to the comments, my solution was sub-optimal.
I'd like to point out, that Erik's answer is probably the best solution. It is short, correctly handles the newlines, and outputs the "Empty Spot" entries as the OP has probably wanted.
Out of educational value, I'll include a version with StringBuilder and manual enumeration that is comparable with Erik's answer in that it is close to the implementation of string.Join():
public string PrintCrate()
{
using (var enumerator = sodaCans.GetEnumerator())
{
if (!enumerator.MoveNext())
return null
var stringBuilder = new StringBuilder();
stringBuilder.Append(enumerator.Current ?? "EmptySpot");
while (enumerator.MoveNext())
{
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(enumerator.Current ?? "EmptySpot");
}
return StringBuilder.ToString();
}
}
sodaCans?string[]?List<string>?String.Joinon a single element of the collection, when in reality you just need to pass the collection intoString.Join-String.Join(Environment.NewLine, sodaCans);. String.Joinreturn string.Join(Environment.NewLine, soda);will exit the method the first time a non-null element is found. The next time you enter the method, it will start over.