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

后端 未结 11 834
广开言路
广开言路 2020-11-29 19:17

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

11条回答
  •  无人及你
    2020-11-29 19:44

    String.Join(";", number.Select(item => item.ToString()).ToArray());
    

    We have to convert each of the items to a String before we can join them, so it makes sense to use Select and a lambda expression. This is equivalent to map in some other languages. Then we have to convert the resulting collection of string back to an array, because String.Join only accepts a string array.

    The ToArray() is slightly ugly I think. String.Join should really accept IEnumerable, there is no reason to restrict it to only arrays. This is probably just because Join is from before generics, when arrays were the only kind of typed collection available.

提交回复
热议问题