tags:

views:

102

answers:

4

Supposed i have an array int[] arr = {1,2,3,4}

I want to convert it into a string. The result i want it to be like this string a = "1,2,3,4";

so can i have something "string a = arr...." to do it, instead of writing a for loop??

Thanks

+1  A: 
string result = string.Join(", ", arr.Select(item => item.ToString()).ToArray());
Except that you don't need all that stuff in the middle. String.Join will work with just an Array
Josh
@Josh: if you're using .NET 4.0.
Michael Petrotta
+2  A: 

You can use String.Join:

int[] arr = new [] { 4, 5, 6, 7 };
string joined = String.Join(",", arr);

See http://msdn.microsoft.com/en-us/library/57a79xd0.aspx for more info.

Michael Shimmins
+8  A: 

As of .NET 4, you can simply do:

var result = string.Join( ",", arr );

In earlier versions,

var result = string.Join( ",", arr.Select( a => a.ToString() ).ToArray() );
tvanfosson
+1  A: 

If you can't use .net 4 (I can't yet as our customers don't deploy it), you can use an extension method. This will work then work for all IEnumerable<T>'swith appropriately implemented .ToString() overrides. You can also pick what sort of seperator you want.

Once you have the below, you can just do string s = myenumerable.Seperated(",");

public static class EnumerableExtender
    {
        public static string Separated<T>(this IEnumerable<T> l, string separator)
        {
            var sb = new StringBuilder();
            var first = true;
            foreach (var o in l)
            {
                if (first) first = false; else sb.Append(separator);
                sb.Append(o.ToString());
            }
            return sb.ToString();
        }
    } 
WOPR
+1 - an example for the pre .NET 4.0 programmer who doesn't want to just create brand new arrays for the sake of making a specific API call.
Alex Humphrey