Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何添加到For循环中而不从一开始就循环?_C#_.net_Winforms - Fatal编程技术网

C# 如何添加到For循环中而不从一开始就循环?

C# 如何添加到For循环中而不从一开始就循环?,c#,.net,winforms,C#,.net,Winforms,我试图在我的组合框中显示一个列表,每次用户输入一个新的船名和船许可证时,它们都会被添加到组合框中 for(int i = 0; i < boatList.Count; i++) { BoatSelector.Items.Add(boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense()); } 预期结果:应将来自用户输入的名称+许可证添加到组合框中 实际结果

我试图在我的组合框中显示一个列表,每次用户输入一个新的船名和船许可证时,它们都会被添加到组合框中

for(int i = 0; i < boatList.Count; i++)
    {
        BoatSelector.Items.Add(boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());
    }     
预期结果:应将来自用户输入的名称+许可证添加到组合框中

实际结果:添加了名称+许可证get,然后for循环返回0并重新添加相同的名称和许可证,同时还添加了任何更新的名称和许可证。

“从新索引开始创建for循环” 我不想在列表的开头存储新的输入,也不想清除列表,我只是想找到一种从新索引开始for循环的方法,而不是再次显示以前的索引

这就是你要找的吗

var last = boatList.Last() // using System.Linq;
var last = boatList[boatList.Count/Count()/Length - 1] // etc. 

BoatSelector.Items.Add(lastItem.GetboatName() + " - " + last.GetboatLicense());
“在新索引上” 我希望存储项,而不是清除项,如何在新索引上启动循环

你是说在列表的开头?如果是这样,您可以使用InsertAt

're添加相同的' 并重新添加相同的名称和许可证,同时添加任何更新的名称和许可证

我认为您多次添加这些项目

for(int i = 0; i < boatList.Count; i++)
{
    BoatSelector.Items.Add(boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());
}   

(... at another time)


for(int i = 0; i < boatList.Count; i++)
{
    BoatSelector.Items.Add(boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());
} 

看起来您只是忘记清除组合框项,即BoatSelector.items.clear;?或者,您可以只添加新项目。这可以通过多种方式实现;其中之一是不在0处开始循环,而是在第一个新索引处开始循环。但是,在添加整个列表之前清除项目应该可以正常工作。@AhmedAbdelhameed我希望存储项目,而不是清除项目,我如何在新索引上启动循环?您能否提供有关添加名称+许可证的更多信息?它添加到了什么?很抱歉造成混淆,我不想在列表的开头存储新的输入,也不想清除列表,我只是想找到一种方法从新索引开始创建for循环,而不是再次显示以前的索引。
for(int i = 0; i < boatList.Count; i++)
{
    BoatSelector.Items.Add(boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());
}   

(... at another time)


for(int i = 0; i < boatList.Count; i++)
{
    BoatSelector.Items.Add(boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());
} 
BoatSelector.Items = boatList
          .Select( item => item.GetboatName() + " - " + item.GetboatLicense())
          .ToList();