| Adam Vandenberg ( @ 2005-11-14 10:43:00 |
| Entry tags: | c#, dotnet, programming |
C#: Join an array of strings
The built-in method String.Join() let's you join an array of strings with a delimiter. Except that it only lets you join an array of strings. string[].
This is an example of inhumane API design, as it requires gross incantations to get an ArrayList of strings joined.
Here's my method to join together an ICollection of any type of object, which are rendered to strings via ToString().
public static string Concat(ICollection items, string delimiter)
{
bool first = true;
StringBuilder sb = new StringBuilder();
foreach(object item in items)
{
if (item == null)
continue;
if (!first)
{
sb.Append(delimiter);
}
else
{
first = false;
}
sb.Append(item);
}
return sb.ToString();
}
Stick this static method wherever you keep your other string utility functions.