MFBM - 2 months ago 4x

Vb.net Question

I was collect data an array with 2 coloumn look like this

`---------------`

Order | Value

---------------

order1 | 45

order2 | 70

order1 | 85

order2 | 32

--------------

How to get all value in the array based conditional where order= order1 only and sum them?

Thank you,

Answer

Using Linq (`Where`

for Conditional) and (`Sum`

for Aggregate Functions):

```
var sum = array.Where(x=> x.Order == "order1").Sum(x=> x.Value);
```

If you really meant a 2-D (Multidimentional) Array, then you can do this:

```
object[,] array =
{
{ "order1", 45 }, { "order2", 70 },
{ "order1", 85 }, { "order2", 32 }
};
decimal Sum = 0;
for(int i = 0; i < array.GetLength(0); i++)
{
if (array.GetValue(i, 0)?.ToString() == "order1")
{
decimal val;
if(decimal.TryParse(array.GetValue(i, 1)?.ToString(), out val))
Sum += val;
}
}
```

Source (Stackoverflow)

Comments