tags:

views:

906

answers:

4

Hi all,

I want to trim the column headers of a CSV file, fields below is an array that contains the header names, where would I place trim()? I've placed it with the foreach loop but VS tells me "cannot assign field because it is a foreach iteration variable". What am I doing wrong?

while ((fields = csv.GetCSVLine()) != null) 
{
    if (header)
    {
     foreach (string field in fields) 
     {
              //field = field.trim(); //VS: "cannot assign field because it is a foreach iteration variable"
       headers.Add(field);
     }
}
+7  A: 

You're trying to change the value of the item you're working on.

Just do

var trimmedField=field.Trim();
headers.Add(trimmedField);
JasonTrue
Or to be more concise you could use headers.Add(field.Trim());
DoctaJonez
Equally sensible, especially if you only use the trimmed version once.
JasonTrue
+9  A: 

You can do it on the same line as the Add() call. No need to overwrite the variable field if you pass the result of Trim() directly to Add().

foreach (string field in fields) 
{
    headers.Add(field.Trim());
}
John Kugelman
Brilliant thanks.
+3  A: 
    foreach (string field in fields) 
    {
      headers.Add(field.Trim());
    }
marcc
+3  A: 

It seems to me that the compiler has already told you exactly what you're doing wrong: You're trying to assign something that's an iteration variable, which you're evidently not allowed to do.

The other answers here have told you what you can do instead: either copy the iteration variable into another variable and trim that, or skip the assignment altogether and add the trimmed value directly.

Rob Kennedy
To be fair, the compiler warning is really unhelpful about what you should be doing, and the MSDN docs really aren't spectacular either. But it all makes a certain sort of sense, once you start understanding how C# handles value and reference types.
andersop