Home > Blockchain >  How do I add up Double Values from multiple String Arrays at the same position? C#
How do I add up Double Values from multiple String Arrays at the same position? C#

Time:08-11

I get Strings like this from my database:

NaN#Nan#44.20216139610997#45.35340149990988#45.44329482112824#45.1593428796393#NaN#NaN

values = SQLvalues.Split('#'); //produces Array you can see in the picture

String Array(String[] values)

Going on further with strings until it ends with about 10 "NaN" Strings again.

What I am doing now is that I sum up all the values from that one Array.

But there will be about 100 more Arrays after this one and I need to add up for example values[8] from this Array with the one at the same position from the next Array.

adding up hope this visualizes better what I need to do

As I am still an apprentice I don´t have much knowledge on all of this.

I´ve been trying to come with a solution for several hours now but I won´t seem to get anything to work here.

Any help would be great!

My Code:

String[] values;
String returnString = "";
List<Double> valueList = new List<Double>();

DateTime time = (DateTime)skzAdapterText.MinTambourChangedTime();

DataTable profilData = skzAdapterText.LoadValuesText(time);

int rowCount = profilData.Rows.Count;

for (int i = 0; i < rowCount; i  )
{
    String SQLvalues = (String)profilData.Rows[i][2];

    values = SQLvalues.Split('#');

    double summe = 0;
    int counter = 0;

    foreach (String tmpRow in values)
    {
        Double value;
        if (double.TryParse(tmpRow, NumberStyles.Float | NumberStyles.AllowThousands, 
        CultureInfo.InvariantCulture, out value)
        && !double.IsNaN(value))
        {
            counter  ;
            summe = summe   value;
        }
    }

    if (summe != 0 && counter != 0)
        valueList.Add(summe / counter);
}

CodePudding user response:

The basic sum can be reduced like so:

values = SQLvalues.Split('#'); 
double sum = values.Where(v => v != "NaN").Select(v => double.Parse(v)).Sum();

For a specific position, say index 8, within many rows:

//Read the data from DB
DataTable profilData = skzAdapterText.LoadValuesText(time);

//parse out the values
var rowValueArrays = // will be a List<double[]>
    profilData.Rows.
    Select(r => r[2].Split('#').Select(v => v == "NaN"?0.0:double.Parse(v)).ToArray()).
    ToList();

// sum the entries at index 8
double sumAt8 = rowValueArrays.Select(r => r[8]).Sum();

You say you are an apprentice, and so the syntax here may be unfamiliar to you and seem difficult to understand. But I want to emphasize the power here. The combination of IEnumerable, lambda expressions, and linq operations reduced the original sample down to two lines of code, and solved the full problem is what is technically three lines (spread out a little for readability). If I wanted to sacrifice any sense of style or maintainability, you could do it in one line. In short, it is will worth your time to learn how to write code this way. With practice, reading and writing code this way can become easy and greatly increase your speed and capability as a programmer.

Finally, I also need to point out that having delimited data like this in a column is an abuse of the database and very poor practice. Schemas like this are considered broken, and need to be fixed.

CodePudding user response:

As you want to sum up the values at the same positions of the arrays, I assume that all these array have the same length. Then first declare the required arrays. You also must probably calculate the average for each array position, so you also need an array for the counter and the averages.

double[] average = null;
int rowCount = profilData.Rows.Count;

if (rowCount > 0) {
    string[] values = ((string)profilData.Rows[0][2]).Split('#');
    int n = values.Length;
    double[] sum = new double[n];
    double[] counter = new double[n];
    for (int i = 0; i < rowCount; i  ) {
        values = ((string)profilData.Rows[i][2]).Split('#');
        for (int j = 0; j < n; j  ) {
            if (double.TryParse(values[j], NumberStyles.Float | NumberStyles.AllowThousands,
                CultureInfo.InvariantCulture, out double value) && !double.IsNaN(value)) {
                counter[j]  ;
                sum[j]  = value;
            }
        }
    }
    average = new double[n];
    for (int i = 0; i < n; i  ) {
        if (counter[i] != 0) {
            average[i] = sum[i] / counter[i];
        }
    }
}

You cannot calculate the average while summing up, since you must divide the total sum by the total count. Therefore, I added another loop calculating the averages at each array position after the summing phase.

  • Related