Home > Back-end >  how to find average with strings c#
how to find average with strings c#

Time:03-30

I need to set a variable as the average of 3 other variables, which are numbers but they are set as strings. How do I do this? I'm using c#, visual studio, windows forms.

The variable i'm trying to set is called skiTime, the variables i'm using to get the average are called skiTime1, skiTime2 and skiTime3.

basically i need the c# version of: skiTime = (skiTime1 skiTime2 skiTime3) / 3

The code where I start (declare? I don't know the word to use) the variables

    List<string> skiTime1 = new List<string>();
    List<string> skiTime2 = new List<string>();
    List<string> skiTime3 = new List<string>();
    string skiTime

The code where i set the value for the variables:

            using (StreamReader sr = new StreamReader("pupilSkiTimes.txt"))
        {

            string line = "";
            while ((line = sr.ReadLine()) != null)
            {
                string[] components = line.Split("~".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                skiTime1.Add(components[2]);
                skiTime2.Add(components[3]);
                skiTime3.Add(components[4]);
            }
            sr.Close();
        }

I need to display skiTime1, skiTime2 and skiTime3 in a data grid view, so i think they need to be strings, if i'm not mistaken. skiTime will only be used in another calculation so maybe it can be turned into an int. I don't really know what i'm doing and only got this far because of tutorials, help.

I can post the whole code if this question is too confusing or doesn't have enough information.

CodePudding user response:

You need to parse the strings to decimals then calculate the average:

List<decimal> avgTime = new List<decimal>();
for (var i = 0; i < skiTime1.Length; i  ) {
  var avg = (decimal.Parse(skiTime1[i])   decimal.Parse(skiTime2[i])   decimal.Parse(skiTime3[i])) / 3;
  avgTime.Add(avg);
}

CodePudding user response:

    public string CalculateAverage(List<string> skiTime1, List<string> skiTime2, List<string> skiTime3)
    {
        List<string> allValues = new List<string>();
        allValues.AddRange(skiTime1);
        allValues.AddRange(skiTime2);
        allValues.AddRange(skiTime3);
        int totalcount = 0;
        int average = 0;

        foreach(var value in allValues)
        {
            totalcount = totalcount   int.Parse(value);
        }

        average = totalcount / allValues.Count();
        return average.ToString();
    }

Function for returning the average value

  • Related