Удалить конкретный элемент из списка - vb.net - PullRequest
1 голос
/ 19 мая 2019

Я все еще пишу новое кодирование и работаю над небольшим приложением, чтобы сгладить некоторые процессы.

Я пытаюсь удалить определенную запись из списка.

Это пример того, что содержит список: 54 54 56 56 58 60 60

Как я могу удалить записи, которые не повторяются?В этом случае 58 будет удалено.

Количество записей в списке может варьироваться от 1 до 8.

Я пробовал несколько вещей с циклическим перемещением по списку, но ничего не былоблизко, чтобы решить проблему.

 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

Что я делаю не так?Заранее спасибо!

1 Ответ

0 голосов
/ 19 мая 2019

Это решение не слишком элегантно, но оно должно работать для любого количества элементов списка в любом порядке.Вы сильно зависели от порядка и группировки списка.

Комментарии в строке.

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...