jsg jsg - 29 days ago 7
ASP.NET (C#) Question

List into a formatted string

I've got a very simple problem but can't seem to figure it out. I've created a list of strings. But i want to format the list into a string that looks like an array.

So for example this is my list

List<string> testData = new List<string> ();
testData.Add("test 1");
testData.Add("test 2");


I want to then format all the data into a string hopefully to look like this:

['test 1', 'test 2']


Ive tried to use a string.Join but that doesnt get the results I'm looking for.

Answer

Ive tried to use a string.Join but that doesn't get the results I'm looking for.

That's true. However, string format can help:

var res = "[" + string.Join(", ", testData.Select(s => $"'{s}'")) + "]";

Prior to C# 6, you would need to use string.Format explicitly:

var res = "[" + string.Join(", ", testData.Select(s => string.Format("'{0}'", s))) + "]";
Comments