views:

3829

answers:

4

I have the following string array:

var sa = new string[] {"yabba","dabba","doo"};

I can convert it to "yabba, dabba, doo" it using string.Join() but what is the super-cool LINQ way of doing it? The Join extension method seems promising but for a novice like me very confusing.

+17  A: 

Have you looked at the Aggregate extension method?

var sa = (new[] { "yabba", "dabba", "doo" }).Aggregate((a,b) => a + "," + b);
Robert S.
That's probably slower than String.Join(), and harder to read in code. Does answer the question for a "LINQ way", though :-)
C. Lawrence Wenham
Yeah, I didn't want to taint the answer with my opinions. :P
Robert S.
It's unquestionably quite a bit slower, actually. Even using Aggregate with a StringBuilder instead of concatenation is slower than String.Join.
Joel Mueller
+21  A: 

Why use Linq?

string[] s = {"foo", "bar", "baz"};
Console.WriteLine(String.Join(", ", s));

That works perfectly and accepts any IEnumerable<string> as far as I remember. No need Aggregate anything here which is a lot slower.

Armin Ronacher
because learning linq is cool
George Mauer
Learning LINQ may be cool, and LINQ may be a cute means to accomplish the end, but using LINQ to actually get the end result would be bad, to say the least, if not outright stupid
Jason Bunting
It does not accept `IEnumerable<string>`, I'd have to test, but I'm not sure if using `IEnumerable<string>::ToArray` to feed `string::Join` would be more efficient than `IEnumerable<string>::Aggregate` in cases where you don't have an array handy.`public static string Join(string separator, string[] value);` `public static string Join(string separator, string[] value, int startIndex, int count);`
joshperry
.NET 4.0 has an IEnumerable<string> and IEnumrable<T> overload, which will make it much easier to use
Cine
+5  A: 

I always use the extension method:

public static string JoinAsString<T>(this IEnumerable<T> input, string seperator)
{
    var ar = input.Select(i => i.ToString()).ToArray();
    return string.Join(seperator, ar);
}
Kieran Benton
A: 

I blogged about this a while ago, what I did seams to be exactly what you're looking for:

http://ondevelopment.blogspot.com/2009/02/string-concatenation-made-easy.html

In the blog post describe how to implement extension methods that works on IEnumerable and are named Concatenate, this will let you write things like:

var sequence = new string[] { "foo", "bar" };
string result = sequence.Concatenate();

Or more elaborate things like:

var methodNames = typeof(IFoo).GetMethods().Select(x => x.Name);
string result = methodNames.Concatenate(", ");
Patrik Hägne