Davis Jahn
Davis Jahn

Reputation: 573

Converting NaN Value into Empty String in C#

I hope this is not a dumb question but I'll try my best to explain.

I read average values from a database and write them into a matrix, I did a for loop to attach the zeros into the matrix so I can see if the following coordinate has a value or not.

Here is my problem:

I need to calculate the average values without adding the zeros from my for loop now. I simply deleted the for loop but now I have a NaN value in my console.

Is there anyway to convert/to filter the NaN value into an Empty string?

            for (int y = 1; y <= koordinaten.Laenge; y++)
            {
                for (int x = 1; x <= koordinaten.Breite; x++)
                {

                    var sK = sensorKoordinaten
                        .Where(sKoordinaten =>
                            sKoordinaten.XKoordinate == x && sKoordinaten.YKoordinate == y)
                        .DefaultIfEmpty(new Sensor())
                        .FirstOrDefault();

                    var messung = results.Where(messungAVG => messungAVG.IDSensor == sK.ID).ToList();
                    var anzahl = DBHelper.GetAnzahlFromMessungKopf(idmessung);

                    double summe = 0;
                    double ergebnis = 0;
                    int d;

                    //Berechnet den Mittelwert
                    for (d = 0; d < messung.Count; d++)
                    {
                        summe += messung[d].Messwert;
                    }
                    ergebnis = summe / d;

                    Console.Write($" {ergebnis.ToString("N2")} ");
                }
                Console.Write("\n");
            }
            Console.ReadKey();

Upvotes: 1

Views: 700

Answers (1)

aloisdg
aloisdg

Reputation: 23521

You got an error because messung is empty.

if (messung.Any()) // same logic than `if (messung.Count > 0)` as @Matthew Watson said
{
    // by the way linq can handle sum
    // ergebnis = messung.Sum(x => x.Messwert) / messung.Count;
    // in fact you can go further, linq includes Average
    ergebnis = messung.Average(x => x.Messwert);
}

Upvotes: 1

Related Questions