0

Please help on converting a list of objects got from DB into substrings separated by a comma

Take for example I have a sample code below:

List<string> CategoryNames = new List<string>(); CategoryNames.Add("myName1"); CategoryNames.Add("myName2"); CategoryNames.Add("myName3"); 

I want to convert CategoryNames into a format like this

"myName1","myName2","myName3"

From the above CatgoryNames happen to be retrieved from db.

var categoryNames = _context.BillingCategory.ToList(); 

How do I convert the categoryNames into substrings as shown above? Any help will be appreciated.

6
  • Do you mean "myName1,myName2,myName3"? Commented Feb 19, 2020 at 12:01
  • Just to doublecheck: Do you really want the result to contain quotes as well like this: "myName1","myName2","myName3" or you just want to get something like this?: "myName1 , myName2 , myName3" Commented Feb 19, 2020 at 12:01
  • 3
    string.Join seems like an answer.... but please clarify requirements Commented Feb 19, 2020 at 12:03
  • Yes i want the format to contain quotes like ``` "myName1","myName2","myName3"``` Commented Feb 19, 2020 at 12:04
  • string.Join("," CategoryNames); would only give me a format like this "myName1,myName2,myName3" Commented Feb 19, 2020 at 12:05

3 Answers 3

2

You can use String.Join() method by combining with LINQ for preserving the quotes before joining:

var result = String.Join(",", CategoryNames.Select(item => $"\"{item}\"")); 

And here is the clearer version of the code if you don't linke singleliner:

var QuotedCategroyNames = CategoryNames .Select(item => $"\"{item}\""); var result = String.Join(",", QuotedCategroyNames); 
Sign up to request clarification or add additional context in comments.

2 Comments

working, but the output is this \"myName1\",\"myName2\",\"myName3\" is this how it should be
Yep, if you are looking from the IDE, it will be shown that way (because it escapes the quote character there). But you can do Console.WriteLine(result); or put the result in the UI, and you'll see the desired result.
0

Use LINQ Select to enclose all names in quotes, then string.Join to merge back into a comma separated string.

string.Join(',', CategoryNames.Select(n => '"' + n + '"')); 

Comments

0

You can use string.Join() and concat with the double quotes character :

var serialized = $@"""{ string.Join(@""",""", CategoryNames) }"""; // "myName1","myName2","myName3" 

Try it yourself

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.