I am a very beginner of C# and programming. I am trying to calculate a few DateTime
variables. The first one is called dDate
and second dDate1
(the previous day of dDate
), third dDate2
(the second previous day of dDate
, i.e., the previous day of dDate1
), the fourth dDate3
(the third previous day of dDate
, i.e., the second previous day of dDate1
and the previous day of dDate2
). They must be not holidays or weekends!
I've had all holidays and weekends stored in a dictionary called nd<DateTime, string>
. The key DateTime
has a series of date from 2011-01-01
to 2013-01-01
, step by one day and the value string
is either TR
or NT
, a string variable but not boolean. If it is weekend or holiday, string is NT
, otherwise TR
.
What I am trying to do is when dDate
is weekend or holiday, minus one day. For example, dDate
is 2012-01-02
which is a holiday, change dDate
to 2012-01-01
, and because it is weekend (Sunday), change it to 2011-12-31
, and it is weekend again, change dDate
to 2011-12-30
. Same to dDate1
, dDate2
and dDate3
.
The problem here is my code works fine for dDate
. But it gives an error:
the given key was not present in the dictionary
when I am doing the same thing for dDate1
, dDate2
or dDate3
. The code is attached below:
private Dictionary<DateTime, string> noDates;
...
noDates = new Dictionary<DateTime, string>();
public void ImportNoDate()
{
string str;
string[] line = new string[0];
while ((str = reader.ReadLine()) != null)
{
line = str.Split(',');
String date = line[1];
String flag = line[2];//flag is "NT" or "TR"
String[] tmp = date.Split('-');
date = Convert.ToInt32(tmp[0]) + "-" + Convert.ToInt32(tmp[1]) + "-" + Convert.ToInt32(tmp[2]);
DateTime noDate = DateTime.Parse(date);
noDates.Add(noDate, flag);
}
}
public void ImportdDate()
{
...
DDates dd = new DDates(dDate, noDates); //dDate is defined similar to noDate, it is just another //series of date
}
//DDates is an auxiliary cs file called DDates.cs
public DDates(DateTime dd, Dictionary<DateTime, string> nd)
{
dDate1 = dDate.AddDays(-1);
dDate1 = dDate.AddDays(-2);
dDate3 = dDate.AddDays(-3);
// dDate is imported from data file and has been Parse
// to DateTime and it is something like
// 2012-01-01 12:00:00 AM
if (nd.ContainsKey(dDate))
{
while (nd[dDate].Contains("NT"))
{
dDate = dDate.AddDays(-1);
}
}
//It works fine till here:
if (nd.ContainsKey(dDate1))
{
//It gives "the given key was not present in the dictionary" here:
while (nd[dDate1].Contains("NT"))
{
dDate1 = dDate1.AddDays(-1);
}
}
}