我有一个名为 result 的变量,它是一个
List<List<string>>
我想解析每个元素并修复它(删除空格等)
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'
我该如何解决这个问题?
最佳答案
基本上你不必使用foreach
。 .NET 中的迭代器基本上是只读的。例如:
for (int i = 0; i < tr.Count; i++)
{
string td = tr[i];
Console.Write("[{0}] ", td);
tr[i] = CleanStrings(td);
}
(请注意,我使用了变量 i
,您正在递增但没有使用它。)
或者,考虑使用 LINQ:
res = res.Select(list => list.Select(x => CleanStrings(x)).ToList())
.ToList();
请注意,这会创建一个新列表,其中包含新列表,而不是改变任何现有列表。
关于c# - 如何修复 List<List<string>> 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12080240/