开发者

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&l开发者_运维问答t;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


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.


Why not

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

or

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


Use join and then add characters in front and after as needed:

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

will get you

[First],[Second],[Last]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜