Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add quotes at the beginning and end of each element in list using LINQ

Tags:

c#

linq

I have a list of strings that I want to encapsulate in quotes and separate with comma and output as single string.

Right now I got only the comma part like so string.Join(",", list);. This generates output like so Id, Name, Price. However I want to add quotes to every item so it will output it like so "Id", "Name", "Price".

Right now I'm looping through every item in list copying it's value and then adding the quotes but I suspect it is possible to do using LINQ.

like image 757
Stan Avatar asked Nov 21 '13 15:11

Stan


2 Answers

Try this

String.Join(",", myList.Select(x => String.Format("\"{0}\"", x));
like image 63
David Pilkington Avatar answered Nov 19 '22 13:11

David Pilkington


I suspect it is possible to do using LINQ

You are correct:

var result = string.Join(",", list.Select(s => '"' + s + '"') );

Right now I'm looping through every item in list copying it's value and then adding the quotes

Well, that's what Linq is doing behind-the-scenes; it's just wrapping it in a .Select extension method.

like image 38
D Stanley Avatar answered Nov 19 '22 14:11

D Stanley