简体   繁体   中英

Keep last N items and remove other items from ListBox

I have a C# Winform with a ListBox. I am trying to remove all the items except the last 5 items. The ListBox sort is set to Ascending.

The items in the ListBox look like the following:

2016-3-1
2016-3-2
2016-3-3
2016-3-4
...
2016-03-28

Here is my code to remove the beginning items.

for (int i = 0; i < HomeTeamListBox.Items.Count - 5; i++)
{
    try
    {
        HomeTeamListBox.Items.RemoveAt(i);
    }
    catch { }
}

I've also tried HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[i]);

While there are more than n items in the list, you should remove items from start of the list.
This way you can keep the last n items of ListBox :

var n = 5; 
while (listBox1.Items.Count > n)
{
    listBox1.Items.RemoveAt(0);
}

Your index i is going to increase by one each time it loops, but you are going to be removing an element each time you loop. What you want to do is remove each element at index 0 for the first 5 passes. So using your current For Loop

HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[0]);

Is what you want in the body.

This should work for you;

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM