As the title says: Why does string.Join
need to take an array instead of an IEnumerable? This keeps annoying me, since I have to add a .ToArray() when I need to create a joined string from the result of a LINQ expression.
My experience tells me that I'm missing something obvious here.
In C#, Join() is a string method. This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. This method can be overloaded by passing different parameters to it.
The Join() method in C# is used to concatenate all the elements of a string array, using the specified separator between each element.
In C#, all collections (eg lists, dictionaries, stacks, queues, etc) are enumerable because they implement the IEnumerable interface. So are strings. You can iterate over a string using a foreach block to get every character in the string.
To join elements of given string array strArray with a delimiter string delimiter , use String. join() method. Call String. join() method and pass the delimiter string delimiter followed by the string array strArray .
Upgrade to .NET 4.0 and use the overload that accepts an IEnumerable<string>
. Otherwise, just accept that it was a long outstanding problem that wasn't addressed until .NET 4.0. You can fix the problem by creating your own extension method too!
public static class StringEnumerableExtensions {
public static string Join(this IEnumerable<string> strings, string separator) {
return String.Join(separator, strings.ToArray());
}
}
Usage:
IEnumerable<string> strings;
Console.WriteLine(strings.Join(", "));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With