1

I have five values where it is possble that one or multiple values are 0. There is a minimum of two values greater than 0.

What is, using VB.net, the easiest and cleanest way to find the smallest value of these values and ignore values that are 0?

EDIT: I am this far:

'get smalles value that is not 0
Dim heights As List(Of Double) 
heights.Add(sectionHeight1)
heights.Add(sectionHeight2)
heights.Add(sectionHeight3)
heights.Add(sectionHeight4)
heights.Add(sectionHeight5)
        
For i = 0 To 4 Step 1
    If heights(i) = 0 Then
        heights.RemoveAt(i)
    End If
Next
lonnebol
  • 67
  • 1
  • 7
  • have u a try to show? Why no put it in list and make a link query where xx>0 with order by and select first – YannickIngenierie Mar 12 '21 at 12:34
  • I added to my post what I already have. – lonnebol Mar 12 '21 at 12:41
  • 1
    Side note. In your original code above, when you want to remove items from a list while iterating over them, go BACKWARDS. – Idle_Mind Mar 12 '21 at 13:37
  • @Idle_Mind Can you tell me why backwards is better? I am still learning. – lonnebol Mar 15 '21 at 08:37
  • Because when moving forwards, as you delete an item, everything shifts down to fill the deleted slot. This means you have to REPEAT that same index as it has something new in it. This does not occur when you iterate BACKWARDS. If you delete an item when moving backwards, everything before that spot has not moved so you can simply decrement your index like normal. – Idle_Mind Mar 15 '21 at 18:22

1 Answers1

3

That's exactly the kind of problem that's best solved with LINQ:

Dim minValueIgnoring0 = heights.Where(Function(h) h <> 0).Min()

Alternative syntax:

Dim minValueIgnoring0 = (From h in heights Where h <> 0).Min()

(Note that you might need to add Imports System.Linq at the top of your source file.)


Note that LINQ can operate on arrays as well, so you don't even need the list:

Dim heights = {sectionHeight1, sectionHeight2, sectionHeight3, sectionHeight4, sectionHeight5}
Dim minValueIgnoring0 = heights.Where(Function(h) h <> 0).Min()

Learn more:

Heinzi
  • 167,459
  • 57
  • 363
  • 519