In C#, is there a more straightforward way of concatenating an array of ints to a string than iterating through the array and adding each int to the string one at at time? Like string.join() (but that takes an array of strings).
string IntsToString(int[] intArray, char delimter = ' ')
{
StringBuilder builder = new StringBuilder("");
foreach(int oneInt in intArray)
{
builder.Append(oneInt.ToString());
builder.Append(delimter);
}
// remove the last delimeter;
builder.Remove(sb.Length-1,1);
return builder.ToString();
}
Without delimiter between the values:
int[] integers = {3, 5, 6, 2, 3};
string word = integers.Select(i => i.ToString()).Aggregate((i, j) => i + j);
With delimiter:
int[] integers = {3, 5, 6, 2, 3};
string delimiter = ", ";
string word = integers.Select(i => i.ToString()).Aggregate((i, j) => i + delimiter + j);
Alternative with string.join:
int[] integers = {3, 5, 6, 2, 3};
string word = string.Join(", ", integers.Select(i => i.ToString()).ToArray());
I like the join better than Aggregate since your only creating accumlater string. With Aggregate you recopying the string into a new accumulator each time since strings are immutable.
Thank you, takatok, I was unaware of StringBuilder or the performance hit that can come from modifying a String repeatedly.
Thank you, Piflik. With the string.join version I’m getting “error CS1061: Type int[ ]' does not contain a definition for Select’ and no extension method Select' of type int[ ]’ could be found”. Am I missing something?
It’s in Ling namespace, add System.Linq to your using statements.
Thank you!