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

发布时间 2023-03-30 17:34:18作者: 清和时光

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

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(',')