How to join int[] to a character separated string in .NET?

var ints = new int[] {1, 2, 3, 4, 5};
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
Console.WriteLine(result); // prints "1,2,3,4,5"

EDIT: As of (at least) .NET 4.5,

var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());

is equivalent to:

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

EDIT:

I see several solutions advertise usage of StringBuilder. Someone complaints that Join method should take an IEnumerable argument.

I'm going to disappoint you :) String.Join requires array for a single reason - performance. Join method needs to know the size of the data to effectively preallocate necessary amount of memory.

Here is a part of internal implementation of String.Join method:

// length computed from length of items in input array and length of separator
string str = FastAllocateString(length);
fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here
{
    UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
    buffer.AppendString(value[startIndex]);
    for (int j = startIndex + 1; j <= num2; j++)
    {
        buffer.AppendString(separator);
        buffer.AppendString(value[j]);
    }
}

I'm too lazy to compare performance of suggested methods. But something tells me that Join will win :)


Although the OP specified .NET 3.5, people wanting to do this in .NET 2.0 with C#2 can do this:

string.Join(",", Array.ConvertAll<int, String>(ints, Convert.ToString));

I find there are a number of other cases where the use of the Convert.xxx functions is a neater alternative to a lambda, although in C#3 the lambda might help the type-inferencing.

A fairly compact C#3 version which works with .NET 2.0 is this:

string.Join(",", Array.ConvertAll(ints, item => item.ToString()))

One mixture of the two approaches would be to write an extension method on IEnumerable<T> which used a StringBuilder. Here's an example, with different overloads depending on whether you want to specify the transformation or just rely on plain ToString. I've named the method "JoinStrings" instead of "Join" to avoid confusion with the other type of Join. Perhaps someone can come up with a better name :)

using System;
using System.Collections.Generic;
using System.Text;

public static class Extensions
{
    public static string JoinStrings<T>(this IEnumerable<T> source, 
                                        Func<T, string> projection, string separator)
    {
        StringBuilder builder = new StringBuilder();
        bool first = true;
        foreach (T element in source)
        {
            if (first)
            {
                first = false;
            }
            else
            {
                builder.Append(separator);
            }
            builder.Append(projection(element));
        }
        return builder.ToString();
    }

    public static string JoinStrings<T>(this IEnumerable<T> source, string separator)
    {
        return JoinStrings(source, t => t.ToString(), separator);
    }
}

class Test
{

    public static void Main()
    {
        int[] x = {1, 2, 3, 4, 5, 10, 11};

        Console.WriteLine(x.JoinStrings(";"));
        Console.WriteLine(x.JoinStrings(i => i.ToString("X"), ","));
    }
}

Tags:

C#

.Net

.Net 3.5