Modrisco Modrisco - 1 year ago 71
Node.js Question

How do I calculate the average of an array?

Public Class Form1
Dim x As Integer
Dim y(9) As Double
Dim average As Double
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For x = 0 To 9
y(x) = x
average = y(9) / 10
Label1.Text = average
End Sub
End Class

I'm having trouble trying to calculate the average of 0 to 9 array, I realize that my code is only going to calculate 9 divided by 10, How do I proceed with calculating the average of the 10 numbers?

Answer Source

Use Linq...

Dim average As Double = y.Average()

Another thing you can do with Linq is exclude certain values from your average. Take this example that sets 9 items in myNumbers() to 10 and then sets the 10th one to zero. I use Linq to first filter for numbers greater than zero then I perform the Average aggregate.

Dim myNumbers(9) As Double
For i As Integer = 0 To 8 Step 1
    myNumbers(i) = 10
Next i

myNumbers(9) = 0

Dim average As Double = myNumbers.Where(Function(num) num > 0).Average()
'Optionally, you could also do it this way:
Dim average2 As Double = (From num In myNumbers
                          Where num > 0).Average()

It gets even better when you use classes. Consider this class Thing:

Public Class Thing
 Public Name As String = ""
 Public Number As Double = 0

 Public Sub New (name As String, number As Double)
    Me.Name= name
    Me.Number = number
 End Sub
End Class 

I can create a collection of that class and the .Where becomes even more powerful. In this example I'm averaging Thing.Number by Thing.Name

Dim things As List(Of Thing) = New List(Of Thing)()
things.Add(New Thing("Michael", 10))
things.Add(New Thing("Michael", 5))
things.Add(New Thing("Michael", 7))
things.Add(New Thing("Michael", 9))
things.Add(New Thing("Rian", 10))
things.Add(New Thing("Rian", 10))
things.Add(New Thing("Rian", 10))

Dim AverageMichael As Double = things.Where(Function(thing) thing.Name = "Michael").Average(Function(thing) thing.Number)
Dim AverageRian As Double = things.Where(Function(thing) thing.Name = "Rian").Average(Function(thing) thing.Number)


A side note
If you're a .NET developer and you'd like to learn to use Linq or you simply need an easy environment to test .NET code then I highly recommend LinqPad. I used LinqPad for all the code in this post.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download