Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix data in List<List<string>>

Tags:

c#

list

I have a variable called result which is a

List<List<string>>

I want to parse each element and fix it (remove white spaces, etc)

            i = 0;
            foreach (List<string> tr in res)
            {
                foreach (string td in tr)
                {
                    Console.Write("[{0}] ", td);
                    td = cleanStrings(td); // line with error
                    i++;
                }
                Console.WriteLine();
            }

    public string cleanStrings(string clean)
    {
        int j = 0;                
        string temp = System.Text.RegularExpressions.Regex.Replace(clean, @"[\r\n]", "");
        if (temp.Equals("&nbsp;"))
        {
            temp = " ";
            temp = temp.Trim();
        }
        clean = temp;                        
        return clean;
    }

Error 1 Cannot assign to 'td' because it is a 'foreach iteration variable'

How would I fix this?

like image 974
Cocoa Dev Avatar asked Dec 19 '25 17:12

Cocoa Dev


1 Answers

Basically you have to not use foreach. Iterators in .NET are read-only, basically. For example:

for (int i = 0; i < tr.Count; i++)
{
    string td = tr[i];
    Console.Write("[{0}] ", td);
    tr[i] = CleanStrings(td);
}

(Note that I've used the variable i which you were incrementing but not otherwise using.)

Alternatively, consider using LINQ:

res = res.Select(list => list.Select(x => CleanStrings(x)).ToList())
         .ToList();

Note that this creates a new list of new lists, rather than mutating any of the existing ones.

like image 96
Jon Skeet Avatar answered Dec 21 '25 06:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!