简体   繁体   English

保留最后 N 个项目并从 ListBox 中删除其他项目

[英]Keep last N items and remove other items from ListBox

I have a C# Winform with a ListBox.我有一个带有 ListBox 的 C# Winform。 I am trying to remove all the items except the last 5 items.我正在尝试删除除最后 5 个项目之外的所有项目。 The ListBox sort is set to Ascending. ListBox 排序设置为升序。

The items in the ListBox look like the following: ListBox 中的项目如下所示:

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]);我也试过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.虽然列表中有n个以上的项目,但您应该从列表的开头删除项目。
This way you can keep the last n items of ListBox :这样您就可以保留ListBox的最后n项:

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.您的索引 i 每次循环时都会增加 1,但是每次循环时您都会删除一个元素。 What you want to do is remove each element at index 0 for the first 5 passes.您想要做的是在前 5 次通过时删除索引 0 处的每个元素。 So using your current For Loop所以使用你当前的 For 循环

HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[0]); 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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