ShadySpiritomb
ShadySpiritomb

Reputation: 125

How to find average from multiple lines of a text file

I need to take a number from every line of a text file and find the average. I'm using stream reader to take the number out of a text file, I don't know where to go from here. Here's what I've done so far

using (StreamReader sr = new StreamReader("pupilSkiTimes.txt"))
{
    string line = "";
    while ((line = sr.ReadLine()) != null)
    {
        string[] components = line.Split("~".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        skiTime.Add(components[7]);
    }
    sr.Close();
}

How do I get this to read from every line of the text file, and once that's done, how do I get the average.

In case you need to know, the data I'm trying to read is doubles, e.g "23.43"

Upvotes: 0

Views: 316

Answers (3)

John Alexiou
John Alexiou

Reputation: 29244

Here is how to use LINQ to clean up the code a bit

static class Program
{
    static void Main(string[] args)
    {
        var data = File.ReadAllLines("pupilSkiTimes.txt")
                     .Select((line)=> line.Split("~".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));

        List<double> skiTime = new List<double>();
        foreach (var parts in data)
        {
            if (double.TryParse(parts[7], out double x))
            {
                skiTime.Add(x);
            }

        }

        double average = skiTime.Average();
    }

}

Upvotes: 0

Maytham Fahmi
Maytham Fahmi

Reputation: 33387

Here is how I will do it, as you mentioned in comments components[7] are double data that you read from the file.

We need to parse it to double, sum it up and divide it by the counting time we are able to parse the number in the file. If the number is not parsed and you want the total average of all lines then move the count out of the if statement.

using (StreamReader sr = new StreamReader("pupilSkiTimes.txt"))
{
    string line;
    double sum = 0;
    int count = 0;
    while ((line = sr.ReadLine()) != null)
    {
        string[] components = line.Split("~".ToCharArray(),
            StringSplitOptions.RemoveEmptyEntries);
        if (double.TryParse(components[7], out var result))
        {
            count++;
            sum += result;
        }
    }
    sr.Close();

    var average = sum / count;

    Console.WriteLine(average);
}

Upvotes: 2

AwatITWork
AwatITWork

Reputation: 586

I think the handy method for this situation like this is useful hopefully you use it, I am using a similar this in my codes.

I am passing FilePath, Separator, and index value

    static double getAvgAtIndex(string fPath, char seperator, int index)
    {
        double sum = 0;
        int counter = 0;

        using (StreamReader sr = new StreamReader(fPath))
        {

            string line = "";
            while ((line = sr.ReadLine()) != null)
            {
                double rawData = 0;
                string[] lineData = line.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
                double.TryParse(lineData[index], out rawData);

                sum += rawData;
                counter++;
            }
            sr.Close();
        }

        return sum / counter;
    }

Usage of this,

    static void Main(string[] args)
    {
        Console.WriteLine("The Avg is: {0}", getAvgAtIndex(@"..\myTextFile.txt", '~' ,1)); 
        // The Avg is: 34.688
    }

Upvotes: 0

Related Questions