Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List into a formatted string

Tags:

c#

asp.net

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.

like image 954
jsg Avatar asked Dec 18 '22 12:12

jsg


2 Answers

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))) + "]";
like image 101
Sergey Kalinichenko Avatar answered Dec 24 '22 01:12

Sergey Kalinichenko


var result = "[" + String.Join(", ", testData.Select(c => "'" + c + "'")) + "]";
like image 22
selami Avatar answered Dec 24 '22 01:12

selami