Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq equivalient to JavaScript's join?

Tags:

c#

linq

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(", ");
like image 823
Adam Rackis Avatar asked Nov 28 '22 03:11

Adam Rackis


2 Answers

Try

string.Join(", ", pluginNames);
like image 88
Davy8 Avatar answered Dec 16 '22 01:12

Davy8


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.

like image 26
Jon Skeet Avatar answered Dec 16 '22 03:12

Jon Skeet