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

后端 未结 11 829
广开言路
广开言路 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:51

    I agree with the lambda expression for readability and maintainability, but it will not always be the best option. The downside to using both the IEnumerable/ToArray and StringBuilder approaches is that they have to dynamically grow a list, either of items or characters, since they do not know how much space will be needed for the final string.

    If the rare case where speed is more important than conciseness, the following is more efficient.

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

提交回复
热议问题