views:

203

answers:

8

I'm looking for the one liner here, starting with:

int [] a = {1, 2, 3};
List<int> l = new List<int>(a);

and ending up with

String s = "1,2,3";
+9  A: 
String s = String.Join(",", a.Select(i => i.ToString()).ToArray());
Yuriy Faktorovich
+1, and you were the first.
Stefan Steinegger
+2  A: 
string.Join(",", l.ConvertAll(i => i.ToString()).ToArray());

This is assuming you are compiling under .NET 3.5 w/ Linq.

Michael Bray
In this case, the `ConvertAll` and `ToArray` methods have nothing to do with LINQ: they belong to the `List<T>` type itself. (But if you did want this code to compile with older versions of C# then you'd need to use `delegate` syntax rather than a lambda for your method argument.)
LukeH
For .NET 4, you can just use `string.Join(",", l)`: http://msdn.microsoft.com/en-us/library/dd992421.aspx
280Z28
+4  A: 
  String.Join(",", l);
womp
+6  A: 
string s = string.Join(",", Array.ConvertAll(a, i => i.ToString()));

or in .NET 4.0 you could try (although I'm not sure it will compile):

string s = string.Join(",", a);
Marc Gravell
+2  A: 
int[] array = {1,2,3};

string delimited = string.Join(",", array);
Kris Krause
you can't string.join on an int[] array. this doesn't compile. EDIT: hmm.. according to another post, you can, if you are in .NET 4.0. You should specify that as a caveat in your post.
Michael Bray
A: 

Another way of doing it:

string s = a.Aggregate("", (acc, n) => acc == "" ? n.ToString() : acc + "," + n.ToString());
primodemus
That's right, this will do the job, although it will be dramatically slower than the various `String.Join` answers on larger lists.
Joel Mueller
+1  A: 
l.Select(i => i.ToString()).Aggregate((s1, s2) => s1 + "," + s2)
Erlend
A: 

I know you're looking for a one liner, but if you create an extension method, all future usage is a one liner. This is a method I use.


public static string ToDelimitedString<T>(this IEnumerable<T> items, string delimiter)
{
    StringBuilder joinedItems = new StringBuilder();
    foreach (T item in items)
    {
        if (joinedItems.Length > 0)
            joinedItems.Append(delimiter);

        joinedItems.Append(item);
    }

    return joinedItems.ToString();
}

For your list it becomes: l.ToDelimitedString(",") I added an overload that always uses comma as the delimiter for convenience.

Matt
I'm not the downvote, but I will point out that this is slower than `String.Join`...
Joel Mueller