Create a list of code lists in a string in C #

Hi everyone, I have a problem trying to convert a list list string to a single line string. But for each element I have to edit in a specific format.

Example

List<string> items = new List<string>(); string result = string.Empty; items.Add("First"); items.Add("Second"); items.Add("Last"); result = string.Join(",", items.ToArray()); Console.WriteLine(result); // Display: First,Second,Last 

But I want to convert something like this:

 [First],[Second],[Last] 

or something like

 --First-,--Second-,--Last- 

I know that there are several methods for writing this code using foreach for loop.

But can he write code by simply changing the entire item in the list collection to a specific line in the template.

Thus, the line of the collection of elements contains from "First" to "\ First /", and "Last" to "Last".

To consider

+4
source share
3 answers

It looks like you want a projection before using Join:

 result = string.Join(",", items.Select(x => "[" + x + "]") .ToArray()); 

Personally, I think this is clearer than making a connection with a more complex delimiter. It seems that you actually have the elements [First] , [Second] and [Third] connected by commas, and not the elements First , Second and Third connected ],[ .

Your second form is equally easy to achieve:

 result = string.Join(",", items.Select(x => "--" + x + "-") .ToArray()); 

Note that you do not need to call ToArray if you are using .NET 4, since it introduced additional overloads to make working with string.Join .

+10
source

Why not

 var result = "--" + string.Join("-,--", items.ToArray()) + "--"; 

or

 var result = "[" + string.Join("],[", items.ToArray()) + "]"; 
+3
source

Use join, and then add the characters in front and after necessary:

 result = "[" + string.Join("],[", items.ToArray()) + "]"; 

will get you

 [First],[Second],[Last] 
+2
source

All Articles