将字符串数组转换为 C# 中的连接字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1304981/
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-06 14:55:40  来源:igfitidea点击:

Convert a string array to a concatenated string in C#

c#arraysstring

提问by Oundless

Is there an easy way to convert a string array into a concatenated string?

有没有一种简单的方法可以将字符串数组转换为连接字符串?

For example, I have a string array:

例如,我有一个字符串数组:

new string[]{"Apples", "Bananas", "Cherries"};

And I want to get a single string:

我想得到一个字符串:

"Apples,Bananas,Cherries"

Or "Apples&Bananas&Cherries"or "Apples\Bananas\Cherries"

"Apples&Bananas&Cherries""Apples\Bananas\Cherries"

采纳答案by Marc Gravell

A simple one...

一个简单的...

string[] theArray = new string[]{"Apples", "Bananas", "Cherries"};
string s = string.Join(",",theArray);

回答by Guffa

The obvious choise is of course the String.Join method.

显而易见的选择当然是 String.Join 方法。

Here's a LINQy alternative:

这是一个 LINQy 替代方案:

string.Concat(fruit.Select((s, i) => (i == 0 ? "" : ",") + s).ToArray())

(Not really useful as it stands as it does the same as the Join method, but maybe for expanding where the method can't go, like alternating separators...)

(实际上并不是很有用,因为它与 Join 方法的作用相同,但可能用于扩展方法无法到达的地方,例如交替分隔符......)

回答by vivek nuna

You can use Aggregate, it applies an accumulator function over a sequence.

您可以使用Aggregate,它在序列上应用累加器函数。

string[] test = new string[]{"Apples", "Bananas", "Cherries"};
char delemeter = ',';
string joinedString = test.Aggregate((prev, current) => prev + delemeter + current);