[英]Keep last N items and remove other items from ListBox
我有一個帶有 ListBox 的 C# Winform。 我正在嘗試刪除除最后 5 個項目之外的所有項目。 ListBox 排序設置為升序。
ListBox 中的項目如下所示:
2016-3-1
2016-3-2
2016-3-3
2016-3-4
...
2016-03-28
這是我刪除開始項目的代碼。
for (int i = 0; i < HomeTeamListBox.Items.Count - 5; i++)
{
try
{
HomeTeamListBox.Items.RemoveAt(i);
}
catch { }
}
我也試過HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[i]);
雖然列表中有n
個以上的項目,但您應該從列表的開頭刪除項目。
這樣您就可以保留ListBox
的最后n
項:
var n = 5;
while (listBox1.Items.Count > n)
{
listBox1.Items.RemoveAt(0);
}
您的索引 i 每次循環時都會增加 1,但是每次循環時您都會刪除一個元素。 您想要做的是在前 5 次通過時刪除索引 0 處的每個元素。 所以使用你當前的 For 循環
HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[0]);
是你想要的身體。
這應該適合你;
if(HomeTeamListBox.Items.Count > 5)
{
var lastIndex = HomeTeamListBox.Items.Count - 5;
for(int i=0; i < lastIndex; i++)
{
HomeTeamListBox.Items.RemoveAt(i);
}
}
for(int i = HomeTeamListBox.Items.Count-5; i>=0; i--)
{
HomeTeamListBox.Items.RemoveAt(i);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.