Something that has been bugging me for a while is that there is no framework function as simple as string.Join( ) for, say, an array of integers. Or at least, there aren’t any that I’m aware of.
There are a bunch of ways to write this, of course, but I like this implementation using custom formatters that I’ve made most of all. It’s obviously not the most efficient way to do it, but I find it extremely useful.
// First, the class that is used as the public interface.
// This provides an object that does the heavy lifting.
public class EnumerableFormatProvider : IFormatProvider
{
private static EnumerableFormatter _formatter =
new EnumerableFormatter();
private static EnumerableFormatProvider _default =
new EnumerableFormatProvider();
public static EnumerableFormatProvider Default
{
get { return _default; }
}
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
{
return _formatter;
}
return null;
}
private EnumerableFormatProvider() { }
}
// Now the class that enumerates the objects and joins them up.
internal class EnumerableFormatter : ICustomFormatter
{
public EnumerableFormatter() { }
public string Format(string format, object arg,
IFormatProvider formatProvider)
{
if (arg == null)
{
return string.Empty;
}
IEnumerable e = arg as IEnumerable;
if (e == null)
{
return arg.ToString();
}
else
{
StringBuilder sb = new StringBuilder();
bool first = true;
IEnumerator en = e.GetEnumerator();
while (en.MoveNext())
{
if (!first)
{
sb.Append(format);
}
first = false;
sb.Append(en.Current.ToString());
}
return sb.ToString();
}
}
}
Here’s one example of how you might use it.
static void Main(string[] args)
{
// prints "1234"
Console.WriteLine(
string.Format(EnumerableFormatProvider.Default, "{0}",
new int[] { 1, 2, 3, 4 })
);
// prints "1,2,3,4"
Console.WriteLine(
string.Format(EnumerableFormatProvider.Default, "{0:,}",
new int[] { 1, 2, 3, 4 })
);
}