Converting a List to a comma separated string

后端 未结 8 1418
深忆病人
深忆病人 2020-12-12 23:04

Is there a way to take a List and convert it into a comma separated string?

I know I can just loop and build it, but somehow I think some of you guys a more cool w

相关标签:
8条回答
  • 2020-12-13 00:04

    Simple solution is

    List<int> list = new List<int>() {1,2,3};
    string.Join<int>(",", list)
    

    I used it just now in my code, working funtastic.

    0 讨论(0)
  • 2020-12-13 00:04

    My "clever" entry:

            List<int> list = new List<int> { 1, 2, 3 };
            StringBuilder sb = new StringBuilder();
            var y = list.Skip(1).Aggregate(sb.Append(x.ToString()),
                        (sb1, x) =>  sb1.AppendFormat(",{0}",x));
    
            // A lot of mess to remove initial comma
            Console.WriteLine(y.ToString().Substring(1,y.Length - 1));
    

    Just haven't figured how to conditionally add the comma.

    0 讨论(0)
提交回复
热议问题