1

I have a List

 private List<string> additionalHeaderMeta = new List<string>();

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.

Brad
  • 11,934
  • 4
  • 45
  • 73
  • 1
    Perhaps `additionalHeaderMeta = additionalHeaderMeta.Select(i => "\"" + i + "\"").ToList();` would be more lucky? – jball Sep 01 '11 at 20:38

2 Answers2

2

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();   
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • Is there no a slick one liner approach to this? I don't know why I didn't figure out your idea here right away...I've just been on this "trying to learn new techniques" kick. – Brad Sep 01 '11 at 20:38
  • @Brad, you can say `list = list.Select(whatever).ToList();` That replaces your existing list with another list of modified elements. See the update. – Anthony Pegram Sep 01 '11 at 20:40
1

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?

Joe White
  • 94,807
  • 60
  • 220
  • 330
  • so... `additionalHeaderMeta = additionalHeaderMeta.Select(i => "\"" + i + "\"");` would do it? – Brad Sep 01 '11 at 20:39
  • 1
    Don't forget the `.ToList()`. – jball Sep 01 '11 at 20:41
  • `Select` returns an `IEnumerable`, which you couldn't assign back into your `List` variable. So if you want to reuse the same variable, yes, you need to add a `.ToList()`. But if you just want to operate on the quoted list, there may be no need to assign it back into your `additionalHeaderMeta` variable. – Joe White Sep 01 '11 at 21:15