Most efficent way of joining strings

前端 未结 11 1751
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 05:51

I need to concatenate a lot of strings alltogether and put a comma between any of them. I have a list of strings

\"123123123213\"
\"1232113213213\"
\"1232131         


        
11条回答
  •  终归单人心
    2021-01-18 06:51

    As @Ekkehard said, use the string.Join.

    However, you do not need the ToArray() because string.Join has an overload for IEnumerable.

    List stringList = new List 
        { "1234567890", "34343434", "4343434" }; 
    
    string outcome = string.Join(",", stringList);
    

    EDIT

    As @Kobi said, this will work only C# 4.0. In 3.5 I would do.

    var s = new StringBuilder(stringList.Count * 8);
    foreach (var item in stringList)
    {
       s.Append(item);
       s.Append(',');
    }
    s.Length -= 1;
    string outcome = stringList.ToList();
    

提交回复
热议问题