从整数 VB.Net 的哈希集中删除元素

Remove elements from hashset of integer VB.Net

我该怎么做,它不像普通列表那样工作。 我必须从列表中删除,其中包含 i.

如果我的列表包含 (2,4,3,13,21,14,15,30)

我要删除前 6 个元素。

  Public randomcards As New HashSet(Of Integer)

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

所以在操作之后,我的列表将变成只有2个元素的15,30。

很遗憾,这不是一个正常的列表,我需要一点帮助

根据定义,HashSet 集合未排序(参见documentation),因此

I want to delete the first 6 element

没有意义。

如果您知道要删除哪个元素(例如数字 14),请使用

randomcards.Remove(14)

同理,如果你想去掉6个随机整数(不保证符合插入顺序!),你可以这样做:

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

这相当乏味,因为您不能通过索引引用 HashSet 中的项目。请记住,您不能通过删除元素来更改 For Each 中的任何集合。

  1. 创建哈希集。

  2. 创建列表。

  3. 将 HashSet 的前 6 个元素添加到列表中。

  4. 遍历列表检查列表中的项目是否在 HashSet 中。如果为真,请将其删除。

    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.