C#“不能分配字段,因为它是一个foreach迭代变量” [英] C# "cannot assign field because it is a foreach iteration variable"
问题描述
我想修剪CSV文件的列标题,下面的字段是包含标题名称的数组,我将在哪里放置trim()?我已经把它放在foreach循环,但VS告诉我不能分配字段,因为它是一个foreach迭代变量。我在做什么错了?
$ b $ pre $ while((fields = csv.GetCSVLine())!= null)
{
if(header)
{
foreach(字段中的字符串字段)
{
// field = field.trim(); // VS:无法赋值字段,因为它是一个foreach迭代变量
headers.Add(field);
$ div $解析方案
可以在 Add()
调用的同一行上执行。如果将 Trim()
的结果直接传递给,则无需覆盖变量
。字段
添加()
foreach(字段中的字段)
{
headers.Add(field.Trim());
}
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);
}
}
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());
}
这篇关于C#“不能分配字段,因为它是一个foreach迭代变量”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!