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(" "))
{
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With