string.Join on a List or other type

前端 未结 7 1604
甜味超标
甜味超标 2020-12-01 10:19

I want to turn an array or list of ints into a comma delimited string, like this:

string myFunction(List a) {
    return string.Join(\",\", a);
}
         


        
7条回答
  •  佛祖请我去吃肉
    2020-12-01 10:36

    This answer is for you if you don't want to venture into the depths of .NET 4.0 just yet.

    String.Join() concatenates all the elements of a string array, using the specified separator between each element.

    The syntax is

    public static string Join(
        string separator,
        params string[] value
    )
    

    Rather than passing your List of ints to the Join method, I suggest building up an array of strings first.

    Here is what I propose:

    static string myFunction(List a) {
        int[] intArray = a.ToArray();
        string[] stringArray = new string[intArray.Length];
    
        for (int i = 0; i < intArray.Length; i++)
        {
            stringArray[i] = intArray[i].ToString();
        }
    
        return string.Join(",", stringArray);
    }
    

提交回复
热议问题