String aggregation and adding separator between each string

June 25th, 2008 by ganton | Print

Today, I found a nice blog - the blog of Peter Petrov. It contains a lovely set of posts of Useful Methods.

In one of its posts there is a really good implementation of string aggregation. There Peter said

Probably we can speed up my implementation by removing the check and removing the separator from the start but I don’t like the idea because it will create a copy of the resulting (big) string.

It is right but reading this I found in my mind an example of how to add a separator between strings without a need of removing the first one separator and to prevent the check of buffer length. Here is an example:

[sourcecode language="csharp"]   
IEnumerator enumerator = values.GetEnumerator();
if (enumerator.MoveNext())
{
buffer.Append(toString(enumerator.Current));
while (enumerator.MoveNext())
{
buffer.Append(separator);
buffer.Append(toString(enumerator.Current));
}
}
[/sourcecode]

The code above can be used instead of foreach {…} equivalent.

[sourcecode language="csharp"]   
foreach (var v in values)
{
if (buffer.Length > 0)
{
buffer.Append(separator);
}
buffer.Append(toString(v));
}
[/sourcecode]

Leave a Reply