views:

53

answers:

4

What is the tersest way to transform an integer array into a string enumerating the elements inline? I'm thinking something like an anonymous function that performs the conversion.

var array = new int[] { 1, 2 }
var s = string.Format("{0}", 
                      new [] 
                      { /*inline transform array into the string "1, 2"*/ });
+5  A: 

Use string.Join. In .NET 3.5 and earlier you need to convert to a string array first; in .NET 4 there's an overload taking IEnumerable<T>. So depending on your version:

.NET 2.0 or 3.0 / C# 2:

string s = string.Join(", ",
    Array.ConvertAll(delegate(int x) { return x.ToString(); });

.NET 2.0 or 3.0 / C# 3:

string s = string.Join(", ", Array.ConvertAll(x => x.ToString());

.NET 3.5 / C# 3:

string s = string.Join(", ", array.Select(x => x.ToString()).ToArray());

(or use the version which works with .NET 2.0 if you prefer).

.NET 4:

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

(I hadn't even seen that before today!)

Jon Skeet
+3  A: 

With String.Join, for .NET 4.0:

var s = String.Join(", ",array);

This works because String.Join now has a overload that takes IEnumerable<T>,

For 3.5, you can use

var s = String.Join(", ", array.Select(n => n.ToString()).ToArray());

For previous .NET versions, see Jon Skeets more complete answer.

driis
@Jon - Wouldn't it use the `Join<T>(string, IEnumerable<T>)` overload?
Nick Craver
+1 - I didn't expect that to work. Doh... hadn't seen the `IEnumerable<T>` overload (new to .NET 4).
Jon Skeet
@Jon Thanks, I edited back to the orignal answer; after I confirmed it with my trusty compiler :-)
driis
+1  A: 

If you're on .Net 4:

var array = new int[] { 1, 2 };
var s = String.Join(", ", array);

There was a String.Join<T>(string, IEnumerable<T>) overloaded added :)

Nick Craver
A: 

ReSharper gives me something like:

    public static string EnumerateToString(this int[] a, string separator)
    {
        return a.Aggregate("", (current, i) => current + i.ToString(separator));
    }
Ben Aston
That will potentially get very slow, as it will be copying the string on every iteration. Basically you end up with O(n^2) complexity.
Jon Skeet