Home > Software design >  Remove elements from hashset of integer VB.Net
Remove elements from hashset of integer VB.Net

Time:01-02

how do i make this work, does not work like a normal list. I have to delete from the list, which contains i.

if my list contains (2,4,3,13,21,14,15,30)

I want to delete the first 6 elemtent.

  Public randomcards As New HashSet(Of Integer)

        For i As Integer = 0 To 5
          randomcards.remove(i)
        Next

so after the operation, my list will become 15,30 with only 2 element.

Unfortunately, this is not a normal list and I would need a little help

CodePudding user response:

By definition, an HashSet collection is not sorted (see the documentation), so

I want to delete the first 6 element

makes no sense.

If you know which element you want to remove (for example the number 14), use

randomcards.Remove(14)

By the same principle, if you want to remove 6 randomic integer (compliance with the insertion order is not guaranteed!), you can do something like this:

Dim fakeList As Integer() = randomcards.ToArray()
For i As Integer = 0 To 5
    randomcards.Remove(fakeList(i))
Next

CodePudding user response:

This is rather tedious because you can't refer to items in a HashSet by index. Keep in mind you can't alter any collection in a For Each by removing an element.

  1. Create a HashSet.

  2. Create a list.

  3. Add the first 6 elements of the HashSet to the list.

  4. Loop through the list checking if the item in the list is in the HashSet. If True remove it.

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim hs As New HashSet(Of Integer) From {2, 4, 3, 13, 21, 14, 15, 30}
        Dim lst As New List(Of Integer)
        Dim counter As Integer
        For Each i In hs
            If counter < 6 Then
                lst.Add(i)
            Else
                Exit For
            End If
            counter  = 1
        Next
        For Each i In lst
            If hs.Contains(i) Then
                hs.Remove(i)
            End If
        Next
        MessageBox.Show(hs.Count.ToString)
        For Each i In hs
            Debug.Print(i.ToString)
        Next
    End Sub
    

@Calaf's answer look superior.
  • Related