C# – Separated string created in loop

.netc++loopssql

I'm searching the best way to create a string separated with another in a loop. I mean, for example, SQL reader:

StringBuilder sb = new StringBuilder();
while(reader.Read())
{
  sb.Append(reader[0]);
  sb.Append("<br />");
}
string result = sb.ToString();
result = result.Remove(result.LastIndexOf("<br />")); // <-

or creating SQL query string;

StringBuilder sb = new StringBuilder();
foreach(string v in values)
{
  sb.Append(v);
  sb.Append(",");
}
string query = sb.ToString()
query = query.Remove(query.LastIndexOf(",")); // <-
query = String.Concat("INSERT INTO [foo] ([bar]) VALUES(", query, ")");

This is the best I have found:

List<string> list = new List<string>;
while(reader.Read())
{
  list.Add(reader[0]);
}
string result = String.Join("<br />", list.ToArray());

Edit: I know about StringBuilder, I didn't used it here just for some clarity. My general idea do not use Remove / LastIndexOf !

Best Solution

I am not a fan of StringBuilder unless you really know that you need to worry about performance. It produces ugly code. I would write it this way...

private IEnumerable<string> ReadAllStrings(DataReader reader)
{
    while(reader.Read())
        yield return reader[0];
}


String.Join("<br />", ReadAllStrings(reader).ToArray());

If I were doing it a lot, I might consider an extension method:

public static class Extensions
{
    public static string JoinWith(this IEnumerable<string> strings, string separator)
    {
        return String.Join(separator, strings.ToArray());
    }
}

Then, my code would look like this:

ReadAllStrings(reader).JoinWith("<br />");