Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write code list collection to string in c#

HI all I have problem when trying to convert list collection string to one line string. But for each item i must edit with 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 wish to convert to something like this:

[First],[Second],[Last]

or something like

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

I know there few technique to write this code using foreach for loop.

But could it write code just change all item in list collection into specific pattern string.

So the items collections string contain like from "First" to "\First/", or "Last" to "''Last'".

Regard

like image 793
Edy Cu Avatar asked Dec 07 '22 01:12

Edy Cu


1 Answers

It sounds like you want a projection before using Join:

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

Personally I think that's clearer than performing a join with a more complicated delimiter. It feels like you've actually got items of [First], [Second] and [Third] joined by commas - rather than items of First, Second and Third joined by ],[.

Your second form is equally easy to achieve:

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

Note that you don't need to ToArray call if you're using .NET 4, as it's introduced extra overloads to make string.Join easier to work with.

like image 84
Jon Skeet Avatar answered Dec 09 '22 13:12

Jon Skeet