【问题标题】:Removing elements from list with condition (VB)从有条件的列表中删除元素(VB)
【发布时间】:2021-03-07 02:54:19
【问题描述】:

我有一个清单

 Dim list As New List(Of Double)

如果差异 > 20,我想删除最后的条目。

我的想法是检查最后 30 个条目:

   Do While index >= list.Count - 30

        If Math.Sqrt((list(index) - list(index + 1)) ^ 2) > 20 Then

            list.RemoveAt(index)
            
            Exit Do
        End If
    Loop

它不会导致我的解决方案。有人可以帮忙吗?非常感谢。

【问题讨论】:

  • 对不起,让我理解得更好。假设您有一个包含 50 个双打的列表。您想从列表的末尾开始删除所有满足您的代码条件的元素,并且在第一个不满足条件的双精度中,您将停止循环(即使有其他元素满足条件较低的索引)?
  • 正是史蒂夫。很抱歉没有完美地描述它。

标签: vb.net list while-loop


【解决方案1】:

我会使用双精度的 LinkedList 来使用类方法和属性,例如 AddFirst、Last、Last.Previous,而不是使用双精度列表

所以让我们假设你有一个 LinkedList 声明如下

Dim list As New LinkedList(Of Double)

你已经使用

向这个列表中添加了元素
list.AddFirst(134.5678)

现在,您可以使用类似这样的内容从列表末尾删除

' You want to have a list of at least 30 elements
Do While list.Count > 30

    ' Last node and the previous one
    Dim dLast = list.Last
    Dim dLastPrev = list.Last.Previous

    ' Evaluate the two elements
    If Math.Sqrt(dLastPrev.Value - dLast.Value) ^ 2 > 20 Then
        ' Remove the last and continue to evaluate the next pair
        list.RemoveLast()
    Else
        ' Stop if the condition is not met.
        Exit Do
    End If
Loop

当然,这也可以使用您当前的列表类型来完成。 还要注意我是如何交换这两个元素来验证的。这样做是为了避免出现 IndexOutOfRangeException

Dim index as Integer = list.Count - 1
Do While index >= list.Count - 30

    Dim prev = index - 1
    If Math.Sqrt((list(prev) - list(index)) ^ 2) > 20 Then
        list.RemoveAt(index)
    else
        Exit Do
    End If
    index = index - 1
Loop

【讨论】:

  • 非常感谢史蒂夫,它现在可以正常工作了!出于某种原因,我不得不声明 Dim index As Integer = list.Count - 1 否则我会得到 IndexOutOfRangeException。
  • 正确,第二个例子我没有测试。
猜你喜欢
  • 2017-12-15
  • 2021-11-16
  • 1970-01-01
  • 2017-08-31
  • 2014-05-06
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
相关资源
最近更新 更多