Home > other >  Very new to C# I need to read only the month in a DD/MM/YYYY style format csv file
Very new to C# I need to read only the month in a DD/MM/YYYY style format csv file

Time:01-24

My program needs to ask the user to say a month Jan (1) Feb (2) and the program has to read the csv file and give the average of the average for each month and day of said month. The csv file format is (date;min;avg;max).

I was expecting it to only give me the numbers for the month chosen, but with my code it is also giving me the number of for example if I say January (1) it will also give me the average of some days on Feb containing the number 1 ex(1, 10, 11... etc.).

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string filepath = "temps.csv";

        try
        {
            string[] lines = File.ReadAllLines(filepath);

            Console.WriteLine("From which month do you wish the avg is calculated? Jan (1) Feb (2)");
            string month = Console.ReadLine();

            double sum = 0;

            int countDay = 0;

            foreach (string line in lines)
            {
                string[] parts = line.Split(';');

                if (parts[0].Contains(month))
                {
                    sum  = double.Parse(parts[2]);

                    countDay  ;
                }
            }
            double average = sum / countDay;

            Console.WriteLine("The avg temp of "   mes   " is: "   average);
        }
        catch (IOException e)
        {
            Console.WriteLine("Error reading file: "   e.Message);
        }
    }
}

CodePudding user response:

Make sure you parse parts[0] to a date, not just treat it as a string

foreach (string line in lines)
{
     string[] parts = line.Split(';');
     var date = DateTime.Parse(parts[0]);
     if (date.Month == month)
     {
           sum  = double.Parse(parts[2]);
           countDay  ;
     }
}

Note the above is oversimplified - consider using ParseExact / TryParseExact and handle parsing errors appropriately.

CodePudding user response:

as I understand the proplem, you shouldn't use foreach beacause you loop for all months, instead you can get the dates using "Where in EF", or if condition. Or, you can replace contain with "==", to get the exact month.

  •  Tags:  
  • c#
  • Related