Throw a string collection at one of these two extension methods, and then set MyTextBox.Text to the returned value.
public static class Extender
{
public static string Delimited(this IEnumerable<string> list, string separator)
{
separator = (string.IsNullOrEmpty(separator)) ? "," : separator;
StringBuilder result = new StringBuilder();
foreach (string item in list)
{
result.AppendFormat("{0}{1}", (result.Length == 0) ? "" : separator, item);
}
return result.ToString();
}
public static string Delimited(this IEnumerable<string> list, char separator)
{
return list.Delimited(separator.ToString());
}
}
Example usage:
string[] stringArray = new string[] { "1", "2", "3" };
List<string> stringList = new List<string>() { "4", "5", "6" };
string x = stringArray.Delimited(",");
string y = stringList.Delimited(';');
You can further modify the methods to accept any type, including complex types, and even specify which property in the object that is to be delimited. I leave that as an exercise for the programmer.
Ah hell, I'll give you the generic version as well. Keep in mind that if you throw anything other than intrinsic types at these versions of the method, you'll only get back the class name (unless, of course, your object overrides the
ToString()
method).
public static string Delimited<T>(this IEnumerable<T> list, string separator)
{
StringBuilder result = new StringBuilder();
foreach (T item in list)
{
result.AppendFormat("{0}{1}", (result.Length == 0) ? "" : separator, item.ToString());
}
return result.ToString();
}
public static string Delimited<T>(this IEnumerable<T> list, char separator)
{
return list.Delimited(separator.ToString());
}
If you wanted to get really fancy with complex objects, you could either use reflection to examine an object's properties and do all the nasty recursion required to handle nested complex objects, or simply deserialize the object into json format, and iterate the properties that way.
Programming is fun!