Home > Net >  Multiply each element in an array with corresponding element in another array
Multiply each element in an array with corresponding element in another array

Time:04-10

So this is what I'm trying to do.

Array1 = {2, 5, 3, 6}
Array2 = {1.5, 1.2, 1.3, 1.4}

Then it will multiply them respectively, like this:

2*1.5  5*1.2  3*1.3  6*1.4

Then the results will be placed in an another array

Results = {3, 6, 3.9, 8.4}

How do I do this in a VB.NET Windows Form Application?

CodePudding user response:

This is easily achievable with LINQ using the IEnumerable.Zip() method:

Dim Results As Double() = Array1.Zip(Array2, Function(d1, d2) d1 * d2).ToArray()
' Print the result
Console.WriteLine(String.Join(",", Results)) ' 3,6,3.9,8.4

Or if you prefer to do it the traditional way, you may use a For loop as follows:

Dim length As Integer = Math.Min(Array1.Length, Array2.Length)
Dim Results(length - 1) As Double
For i = 0 To length - 1
    Results(i) = Array1(i) * Array2(i)
Next
  • Related