PROBLEM: weather.txt contains weather information for every day in January 2018. Each line is formated:
"Date;Precipitation;HighTemp;LowTemp"
1/1/2018;0;29;10
Split and tokenize each line and display data for the date picked in Form Labels.
The problem I'm having is how to check the tokenized DateTime data to see if it matches the DateTime picked from the DateTimePicker so that I can display the correct information in the labels.
Labels in form to hold corresponding data: dateLabel, precipLable, highLabel, lowLabel.
namespace WeatherData2
{
struct WeatherData
{
public DateTime date;
public double precip;
public int highTemp;
public int lowTemp;
}
public partial class Form1 : Form
{
private List<WeatherData> weatherList = new List<WeatherData>();
public Form1()
{
InitializeComponent();
}
private void ReadFile()
{
try
{
StreamReader inputFile;
string line;
WeatherData entry = new WeatherData();
char[] delim = { ';' };
inputFile = File.OpenText("weather.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
DateTime.TryParse(tokens[0], out entry.date);
double.TryParse(tokens[1], out entry.precip);
int.TryParse(tokens[2], out entry.highTemp);
int.TryParse(tokens[3], out entry.lowTemp);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
}
}
If any clarification is need, please let me know. I probably wrote that 10 kinds of confusing. Any help would be greatly appreciated. Thanks.
You can use linq to easily check:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
var pickedDate = dateTimePicker1.Value.ToShortDateString();
if (weatherList.Any(e => e.date == pickedDate))
{
var matching = weatherList.First(e => e.date == pickedDate);
}
}
you also need to make some changes to your loop. right now you are overwriting your entry object for each iteration of the loop and not adding it to you collection.
while (!inputFile.EndOfStream)
{
//create a new instance of entry for each iteration
entry = new WeatherData();
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
DateTime.TryParse(tokens[0], out entry.date);
double.TryParse(tokens[1], out entry.precip);
int.TryParse(tokens[2], out entry.highTemp);
int.TryParse(tokens[3], out entry.lowTemp);
//add the item to the list
weatherList.Add(entry);
}