Search code examples
vb.netlistintervals

Removing everything but an interval of values from a list in VB.net


I have a list

Dim list as New List(Of Double)

It contains values from 0 to 1000. I want to keep the values within the interval [360 ; 720]. The following code works for me, but I am sure that there is a more efficient way:

Dim index As Integer

Do
    list.RemoveAt(index)
Loop Until list(index) > 360

For i = list.Count - 1 To 0 Step -1
    If list(i) > 720 Then
        list.RemoveAt(i)
    End If
Next

Solution

  • This is a one-liner:

    list = list.Where(Function(x) x > 360 AndAlso x <= 720).ToList()
    

    If you're sure the list is sorted, you could also do this, which might run faster:

    list = list.
        SkipWhile(Function(x) x <= 360).
        TakeWhile(Function(x) x <= 720).
        ToList()