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

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 using C# and .NET 3.5.

2022-07-25 20:41:29
Source Share
Answers: 5
String.Join(";", number.Select(item => item.ToString()).ToArray());

We need to transform each of the things to a String prior to we can join them, so it makes good sense to make use of Select and also a lambda expression. This amounts map in a few other languages. After that we need to transform the resulting collection of string back to an array, due to the fact that String.Join just approves a string array.

The ToArray() is a little hideous I assume. String.Join needs to actually approve IEnumerable<String>, there is no factor to limit it to just selections. This is possibly even if Join is from prior to generics, when selections were the only sort of keyed in collection readily available.

2022-07-25 22:06:30

If your array of integers might be huge, you'll improve efficiency making use of a StringBuilder. E.g.:

StringBuilder builder = new StringBuilder();
char separator = ',';
foreach(int value in integerArray)
    if (builder.Length > 0) builder.Append(separator);
string result = builder.ToString();

Edit: When I uploaded this I was under the incorrect impact that "StringBuilder.Append (int value) " inside took care of to add the string depiction of the integer value without developing a string object. This is incorrect: evaluating the method with Reflector reveals that it merely adds value.ToString().

Consequently the only possible efficiency distinction is that this strategy stays clear of one array production, and also releases the strings for trash a little earlier. In technique this will not make any kind of quantifiable distinction, so I've upvoted .

2022-07-25 22:04:50
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"

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

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

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

Here is a part of the 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);
    for (int j = startIndex + 1; j <= num2; j++)
2022-07-25 22:02:09

One combination of both strategies would certainly be to write an expansion method on IEnumerable which made use of a StringBuilder. Below is an instance, with various overloads relying on whether you intend to define the makeover or simply rely upon simple ToString. I've called the method "JoinStrings" as opposed to "Join" to stay clear of complication with the various other sort of Join. Probably a person can think of a far 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;
        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(i => i.ToString("X"), ","));
2022-07-25 21:28:38

I concur with the lambda expression for readability and also maintainability, yet it will certainly not constantly be the most effective alternative. The disadvantage to making use of both the IEnumerable/ToArray and also StringBuilder strategies is that they need to dynamically expand a checklist, either of things or personalities, given that they do not recognize just how much room will certainly be required for the last string.

If the uncommon instance where rate is more vital than brevity, the adhering to is extra reliable.

int[] number = new int[] { 1, 2, 3, 4, 5 };
string[] strings = new string[number.Length];
for (int i = 0; i < number.Length; i++)
  strings[i] = number[i].ToString();
string result = string.Join(",", strings);
2022-07-25 20:49:51