 # Working with Lists in VB component

I’m still trying to learn/understand all the instances surrounding list/tree access with the VB script component. I am trying to create a function that will run through each line but also store/output a result when being compared. The logic is this…

For each line (same list length for x & y),
if x <= 12 output the maximum of the previously indexed y value or current y
otherwise (if x > 12), output the sum of the previously indexed y + current y

I’ve shared the output I am expecting but cannot seem to get it. Can anyone offer their help?

VB (or C# for that matter) does not allow you to work with collections of values automatically. That is, if there’s a method which operates on integers, such as `Math.Max(a, b)`, it cannot be used on collections of integers.

If you have a list, or an array, or an IEnumerable, or …, you have to do the looping yourself.

In certain cases you will be able to write LINQ statements which do iterate like this, but I recommend you stay away from LINQ as a beginner.

In your case you can do two things:

1. Let grasshopper take care of the looping for you. Just remove all your `List(Of Integer)` types and switch them to `Integer`. I am not 100% sure if that’s really an option here because I’m not 100% sure what your code is meant to do.
2. Loop it yourself.

Here’s how it might look.

``````Dim output As New List(Of Integer)
Dim sum As Integer = 0

Dim xMax As Integer = x.Count - 1
Dim yMax As Integer = y.Count - 1
For i As Integer = 0 To Math.Max(xMax, yMax)
(
Dim xValue As Integer = x(Math.Min(i, xMax))
Dim yValue As Integer = y(Math.Min(i, yMax))
If (xValue <= 12) Then
sum = Math.Max(sum, yValue)
Else
sum += yValue
End If
)

A = output
``````

This code is slightly more complicated than your average loop because it needs to be smart enough to not fail when x and y contain a different number of elements. Or, if that’s always indicative of an error, you can check for it ahead of time:

``````If (x.Count <> y.Count) Then
Throw New Exception("x and y must have the same number of elements")
End If

Dim output As New List(Of Integer)
Dim sum As Integer = 0
For i As Integer = 0 To x.Count - 1
(
If (x(i) <= 12) Then
sum = Math.Max(sum, y(i))
Else
sum += y(i)
End If