Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason string.Join needs to take an array instead of an IEnumerable?

Tags:

c#

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.

like image 331
sbi Avatar asked Oct 19 '10 13:10

sbi


People also ask

What is the use of string join in C#?

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.

How to join an array of strings in C#?

The Join() method in C# is used to concatenate all the elements of a string array, using the specified separator between each element.

Does string implement IEnumerable?

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.

How do you join arrays in Java?

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 .


1 Answers

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(", "));
like image 173
jason Avatar answered Oct 23 '22 05:10

jason