我是 C# 和编程的初学者。我正在尝试计算一些DateTime
变量。第一个叫dDate
and second dDate1
(的前一天dDate
),third dDate2
(的前一天dDate
,即前一天dDate1
),第四个dDate3
(前的第三天dDate
,即前第二天dDate1
和前一天) ) dDate2
。他们一定不是假期或周末!
我将所有的假期和周末都存储在一个名为nd<DateTime, string>
. 键DateTime
有一系列日期,从2011-01-01
到2013-01-01
,一步一步,值string
是TR
or NT
,一个字符串变量,但不是布尔值。如果是周末或节假日,则字符串为NT
,否则为TR
。
我想做的是什么时候dDate
是周末或假期,减去一天。比如dDate
是2012-01-02
哪个假期,改成dDate
,2012-01-01
因为是周末(周日),改成2011-12-31
,又是周末,dDate
改成2011-12-30
。与dDate1
和dDate2
相同dDate3
。
这里的问题是我的代码适用于dDate
. 但它给出了一个错误:
字典中不存在给定的键
当我为dDate1
,dDate2
或做同样的事情时dDate3
。代码附在下面:
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);
}
}
}