Une implémentation évolutive et sûre d'une jointure de chaîne énumérable générique pour .NET 3.5. L'utilisation des itérateurs est telle que la valeur de la chaîne de jointure ne soit pas bloquée à la fin de la chaîne. Cela fonctionne correctement avec 0, 1 et plus d'éléments:
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));
Prendre plaisir!