Adam Rackis
Adam Rackis

Reputation: 83358

Linq equivalient to JavaScript's join?

In JavaScript if I have var arr = ["a", "b", "c"] I can say arr.join(','); to get a string containing the comma-delimited list of values. Is there a direct way to do this in Linq?

I know I can use Aggregate ie pluginNames.Aggregate((s1, s2) => s1 + ", " + s2); But that seems a bit clunky. Is there something cleaner? Something hypothetically like

pluginNames.JavaScriptJoin(", ");

Upvotes: 4

Views: 1510

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500225

Just use String.Join - not part of LINQ, just of the framework:

string joined = string.Join(", ", array);

If that's really too clunky for you, you can write an extension method:

public static string JoinStrings(this string[] bits, string separator)
{
    return string.Join(separator, bits);
}

Note that .NET 4 has more overloads for string.Join, including taking sequences (rather than just arrays) and not just of strings.

I would suggest that you don't just use the name Join, as that will look like you're doing an inner join.

Upvotes: 14

BrokenGlass
BrokenGlass

Reputation: 160862

You can use string.Join():

string result = string.Join(",", pluginNames);

Upvotes: 5

David Ly
David Ly

Reputation: 31586

Try

string.Join(", ", pluginNames);

Upvotes: 15

Related Questions