3

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);
        }
}

5 Answers 5

10

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());
}
Sign up to request clarification or add additional context in comments.

Comments

8

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

Just do

var trimmedField=field.Trim();
headers.Add(trimmedField);

2 Comments

Or to be more concise you could use headers.Add(field.Trim());
Equally sensible, especially if you only use the trimmed version once.
3
    foreach (string field in fields) 
    {
      headers.Add(field.Trim());
    }

Comments

3

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.

1 Comment

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.
1

Although the appearance would be less 'modern', its likely about as fast to execute and resource-friendly to simply utilize a For loop in the case described, i.e.:

while ((fields = csv.GetCSVLine()) != null) {
    if (header) {
        for(int ii = 0; ii < fields.Count; ii++) {
            headers.Add(field);
}   }   }

Of course I'm confident the issue was solved this years ago, but am just putting this out there to assist others browsing through. I personally think it's a bit silly we're not allowed to assign values to foreach iterators (I suspect they could easily cover the hurdle (such as it is) at compile and / or run time).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.