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


Question

I have an array of integers:

int[] number = new int[] { 2,3,6,7 };

What is the easiest way of converting these into a single string where the numbers are separated by a character (like: "2,3,6,7")?

I'm in C# and .NET 3.5.

1
98
2/19/2016 10:31:38 AM

Accepted Answer

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 :)

159
7/23/2019 9:50:45 AM

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()))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon