C# 实现List 转字符串并使用逗号隔开

以下代码作为例子来操作:

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

方式1:使用for循环

string result = "";
for (int i = 0; i < list.Count; i++) {
    result = result + list[i] + ",";
}

方式2:使用String.Join

string result = String.Join(",", list);

方式3:使用Linq

string result = list.Aggregate("", (current, s) => current + (s + ","));

以上3中方式都是输出 1,2,3,
可以使用TrimEnd去掉最后一个"," result.TrimEnd(',')
方式3中使用Linq,如果List是string类型的List 可以使用以下写法,末尾不会有逗号

List<string> list = new List<string>() { "hello", "world"};
string result = list.Aggregate((x, y) => x + "," + y);  /// hello,world
posted @ 2023-03-30 17:28  清和时光  阅读(2912)  评论(0编辑  收藏  举报