c#/LINQ中将数组转换为字符串的最短方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/380708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 01:18:57  来源:igfitidea点击:

Shortest method to convert an array to a string in c#/LINQ

c#linqarrays

提问by Loris

Closed as exact duplicate of this question.

作为此问题的完全副本关闭。

I have an array/list of elements. I want to convert it to a string, separated by a custom delimitator. For example:

我有一个数组/元素列表。我想将其转换为字符串,由自定义分隔符分隔。例如:

[1,2,3,4,5] => "1,2,3,4,5"

What's the shortest/esiest way to do this in c#?

在 c# 中执行此操作的最短/最简单的方法是什么?

I have always done this by cycling the list and checking if the current element is not the last one before adding the separator.

我总是通过循环列表并在添加分隔符之前检查当前元素是否不是最后一个来完成此操作。

for(int i=0; i<arr.Length; ++i)
{
    str += arr[i].ToString();
    if(i<arr.Length)
        str += ",";
}

Is there a LINQ function that can help me write less code?

有没有可以帮助我编写更少代码的 LINQ 函数?

采纳答案by Mehrdad Afshari

String.Join(",", arr.Select(p=>p.ToString()).ToArray())

回答by David Schmitt

String.Join(",", array.Select(o => o.ToString()).ToArray());