string.Join on a List<int> or other type
Solution 1:
The best way is to upgrade to .NET 4.0 where there is an overload that does what you want:
String.Join<T>(String, IEnumerable<T>)
If you can't upgrade, you can achieve the same effect using Select and ToArray.
return string.Join(",", a.Select(x => x.ToString()).ToArray());
Solution 2:
A scalable and safe implementation of a generic enumerable string join for .NET 3.5. The usage of iterators is so that the join string value is not stuck on the end of the string. It works correctly with 0, 1 and more elements:
public static class StringExtensions
{
public static string Join<T>(this string joinWith, IEnumerable<T> list)
{
if (list == null)
throw new ArgumentNullException("list");
if (joinWith == null)
throw new ArgumentNullException("joinWith");
var stringBuilder = new StringBuilder();
var enumerator = list.GetEnumerator();
if (!enumerator.MoveNext())
return string.Empty;
while (true)
{
stringBuilder.Append(enumerator.Current);
if (!enumerator.MoveNext())
break;
stringBuilder.Append(joinWith);
}
return stringBuilder.ToString();
}
}
Usage:
var arrayOfInts = new[] { 1, 2, 3, 4 };
Console.WriteLine(",".Join(arrayOfInts));
var listOfInts = new List<int> { 1, 2, 3, 4 };
Console.WriteLine(",".Join(listOfInts));
Enjoy!