首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从列表框中删除特定项目- vb.net

从列表框中删除特定项目- vb.net
EN

Stack Overflow用户
提问于 2019-05-19 21:10:43
回答 1查看 317关注 0票数 1

我仍然是新的编码,我正在开发一个小的应用程序来平滑一些过程。

我正在尝试从列表框中删除某个条目。

这是列表框所包含内容的一个示例: 54 54 56 56 58 60 60

如何删除不重复的条目?在这种情况下,58将被删除。

列表框中的条目数量可以在1到8之间变化。

我用遍历列表框的方法尝试了多种方法,但都无法解决这个问题。

代码语言:javascript
复制
 For i = 0 To ListBox1.Items.Count - 1 Step 2
        If ListBox1.Items(i) <> ListBox1.Items(i + 1) Then
            ListBox1.Items.RemoveAt(i)
        End If
 Next

我做错了什么?提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-20 01:25:21

这个解决方案不是很优雅,但它应该适用于任何顺序的任意数量的列表项。您很大程度上依赖于列表的顺序和分组。

行中的注释。

代码语言:javascript
复制
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Create a list to hold the indexes to remove
    Dim RemoveIndex As New List(Of Integer)
    'put the items in the list box into an array of Integers
    Dim Numbers = (From n In ListBox1.Items
                   Select CInt(n)).ToArray
    'Loop through the numbers that came from the list box
    For i = 0 To Numbers.Count - 1
        '.LastIndexOf looks in the array (starting at the beginning each time) for Numbers(i)
        Dim LastIndex = Array.LastIndexOf(Numbers, Numbers(i))
        'If it is not the item we are searching for 
        If LastIndex <> i Then
            'Add both to the list
            RemoveIndex.Add(LastIndex)
            RemoveIndex.Add(i)
        End If
    Next
    'Remove duplicates from the list. We can't remove the same item twice
    'Order by the highest index first. That way we won't mess up the lower indexes
    'and we will remove the item/index we expect.
    Dim DistinctList = RemoveIndex.Distinct().OrderByDescending(Function(x) x)
    'Loop through the list (remember the highest index is first)
    For Each index In DistinctList
        ListBox1.Items.RemoveAt(index)
    Next
End Sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56208141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档