简体   繁体   中英

Convert a string array to a concatenated string in C#

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"

A simple one...

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

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

Here's a LINQy alternative:

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...)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM