什么是C#方法/语法转换数组一个简单的字符串?数组、字符串、语法、简单

2023-09-04 12:50:35 作者:骑着王八追兔子

我正在寻找的是JavaScript的基本相当于阵列::连接(),让你传递一个分隔符,并使用在所有的返回字符串下标。我可以使用的StringBuilder 或诸如此类的东西肯定是写我自己的功能,但也的必须的东西内置到.NET基础类库。

What I'm looking for is a basic equivalent of JavaScript's Array::join() whereby you pass in a separator character and uses that in its return string of all the subscripts. I could certainly write my own function using a StringBuilder or whatnot, but there must be something built into the .NET BCL.

编辑:的的什么阵的,不一定字符串字符。我想preFER的方法来简单地调用的ToString()每个标对象上。 的string.join()是伟大的,除非你把它传递一个字符串数组。

Array of anything, not necessarily string or char. I'd prefer the method to simply call ToString() on each subscript object. String.Join() is great except that you pass it an array of strings.

推荐答案

如果数组包含字符串,你可以使用的 的string.join() 。如果阵列中不包含字符串,你需要的东西多一点复杂的,所以你可以处理投或转换过程中的每个它​​所包含的项目。

If the array contains strings, you can just use String.Join(). If the array does not contain strings, you'll need something a little more complicated so you can handle the cast or conversion process for each item it contains.

更新:使用@ JaredPar的code为基础,一个更通用的例子:

Update: Using @JaredPar's code as the basis for a more generic example:

char sep = GetSeparatorChar();
object[] toJoin = GetToJoin();
string joined = toJoin.Aggregate((x,y) => x.ToString()+sep.ToString()+y.ToString());

显然,你可以做你想要的X和Y任何在这个例子中得到的字符串看你怎么想。

Obviously you could do anything you wanted to x and y in that example to get the string to look how you wanted.