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 . My general idea do not use StringBuilder, I didn’t used it here just for some clarityRemove / LastIndexOf !
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…
If I were doing it a lot, I might consider an extension method:
Then, my code would look like this: