开发者

How to add quotes around each list element after .add?

开发者 https://www.devze.com 2023-04-01 04:05 出处:网络
I have a List private List<string> additionalHeaderMeta = new List<string>(); 开发者_JS百科

I have a List

 private List<string> additionalHeaderMeta = new List<string>();
开发者_JS百科

and I want to output it to a csv file. All that is working find but it turns out some of the elements I am adding to additionalHeaderMeta might have commas in them sometimes which obviously messes up a csv file. How can I put quotes around each element after the element has been added?

I tried

additionalHeaderMeta.Select(i => "\"" + i + "\"");

But no luck there.


If you want to modify the list in place, simply loop over it.

for (int index = 0; index < list.Count; index++)
    list[index] = /* modify item here */

What you have done is create a query definition which would be lazily evaluated, but you would actually need to iterate over the query. Use the query if you want to actually leave the list unmodified, but simply want to project the data into the modified form.

var query = additionalHeaderMeta.Select(i => "\"" + i + "\"");   
foreach (var item in query)
    do whatever

To simply replace your list with another entirely, use ToList() on the query and assign the result back to your original list.

additionalHeaderMeta = additionalHeaderMeta.Select(i => "\"" + i + "\"").ToList();   


Your example code:

additionalHeaderMeta.Select(i => "\"" + i + "\"");

will work just fine. It will return a new list with the quotes added.

It will not modify the existing list -- is that where your confusion is coming from?

0

精彩评论

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