Un scalabile e sicura implementazione di una stringa enumerabile generica unirsi per .NET 3.5. L'utilizzo degli iteratori è in modo che il valore della stringa di join non sia bloccato alla fine della stringa. Funziona correttamente con 0, 1 e più elementi:
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();
}
}
Utilizzo:
var arrayOfInts = new[] { 1, 2, 3, 4 };
Console.WriteLine(",".Join(arrayOfInts));
var listOfInts = new List<int> { 1, 2, 3, 4 };
Console.WriteLine(",".Join(listOfInts));
Godere!