1

I'm relatively new to c# and I am trying to write a program that finds the mean of every xth value in a file using Streamreader. (For example if I wanted to find the mean of every fifth value in that file)

I written some code that reads the file and splits it into a new line for each comma, and this works fine, when I try and read each specific value.

However I'm struggling to think of a way to find every specific value, such as every 4th one and then find the mean of these and output it in the same program.

    static void Main(string[] args)
    {
        using (var reader = new StreamReader(@"file"))
        {
            List<string> list = new List<string>();
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(',');
                list.Add(values[0]);
            }
        }
    }

Any suggestions or help would be greatly appreciated

Major
  • 11
  • 1
  • Possible duplicate of [How can I get every nth item from a List?](https://stackoverflow.com/questions/682615/how-can-i-get-every-nth-item-from-a-listt) `there are a ton of examples on google if you were to type how to skip every fourth item in a List` for example.. you will need to do the proper casting if your are doing mathematical functions – MethodMan Dec 09 '17 at 21:36
  • You‘ve added some code, but it doesn‘t show that you have tried anything. You still want others to do all your work. – Sefe Dec 09 '17 at 22:06

1 Answers1

0

Try like this;

    static void Main()
    {
        using (var reader = new StreamReader(@"file"))
        {
            int lineNumber = 4;
            bool streamEnded = false;
            List<string> list = new List<string>();
            while (!streamEnded)
            {
                var line = ReadSpecificLine(reader, lineNumber,out streamEnded);
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }
                var values = line.Split(',');
                list.Add(values[0]);
            }
        }
    }
    public static string ReadSpecificLine(StreamReader sr, int lineNumber,out bool streamEnded)
    {
        streamEnded = false;
        for (int i = 1; i < lineNumber; i++)
        {
            if (sr.EndOfStream)
            {
                streamEnded = true;
                return "";
            }
            sr.ReadLine();
        }
        if (sr.EndOfStream)
        {
            streamEnded = true;
            return "";
        }
        return sr.ReadLine();
    }
lucky
  • 12,734
  • 4
  • 24
  • 46
  • I use this and give change the file location so it's correct but I get no output when I run the program. Any idea why? – Major Dec 11 '17 at 18:30
  • "I get no output when I run the program" Do you mean that printing list object to console ? – lucky Dec 11 '17 at 19:09