【问题标题】:Keep last N items and remove other items from ListBox保留最后 N 项并从 ListBox 中删除其他项
【发布时间】:2016-03-27 23:26:03
【问题描述】:

我有一个带有 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]);

【问题讨论】:

  • 代码正确,有什么问题?
  • @AshkanMobayenKhiabani 代码不正确。它绕过了一些项目。例如,使用此代码将不会删除位于索引 1 的项目。 OP 删除索引 0 处的项目,然后项目上升,之前位于索引 1 的项目现在位于索引 0。因此,当 OP 尝试删除索引 1 处的项目时,他会意外地看到位于索引处的项目2 在开始时,被删除等等。

标签: c# .net winforms listbox-control


【解决方案1】:

虽然列表中有超过n 个项目,但您应该从列表的开头删除项目。
这样你就可以保留ListBox的最后一个n项目:

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

【讨论】:

  • 感谢 Reza ,修复了它。
【解决方案2】:

您的索引 i 将在每次循环时增加一,但您将在每次循环时删除一个元素。您要做的是在前 5 次通过中删除索引 0 处的每个元素。所以使用你当前的 For 循环

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

是你想要的身体。

【讨论】:

    【解决方案3】:

    这应该对你有用;

    if(HomeTeamListBox.Items.Count > 5)
    {
        var lastIndex = HomeTeamListBox.Items.Count - 5; 
        for(int i=0; i < lastIndex; i++)
        {
           HomeTeamListBox.Items.RemoveAt(i);
        }
    }
    

    【讨论】:

      【解决方案4】:
      for(int i = HomeTeamListBox.Items.Count-5; i>=0; i--)
      {
          HomeTeamListBox.Items.RemoveAt(i);
      }
      

      【讨论】:

        猜你喜欢
        • 2022-08-10
        • 2014-03-14
        • 1970-01-01
        • 2013-07-10
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-21
        相关资源
        最近更新 更多