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

问题描述 投票:0回答:1

我试图让列表显示在我的组合框中,每当用户输入新的船名和船牌时,他们都会被添加到组合框中。

我已经尝试过使用for循环来完成此操作,但这给了我一个我理解如何修复它的bug。

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

预期结果:用户输入的名称+许可证,应添加到组合框中。

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

c# .net winforms
1个回答
0
投票

'在新索引上'

我希望存储而不是清除项目,我将如何在新索引上开始循环?

您的意思是在列表的开头吗?如果是这样,您可以使用InsertAt

BoatSelector.Items.InsertAt(0,boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());

'重新添加相同'

我认为您要多次添加项目。

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() Items或分配新列表:

BoatSelector.Items = boatList
          .Select( item => item.GetboatName() + " - " + item.GetboatLicense())
          .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.