欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

C# 将 List 转换为用逗号分隔的字符串。

最编程 2024-03-01 18:42:50
...

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

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

推荐阅读