【发布时间】:2013-09-30 21:49:51
【问题描述】:
我是 C# 和编程的初学者。我正在尝试计算一些DateTime 变量。第一个叫dDate,第二个叫dDate1(dDate的前一天),第三个dDate2(dDate的前一天,即dDate1的前一天),第四个dDate3(dDate的前三天,即dDate1的前第二天和dDate2的前一天)。他们一定不是假期或周末!
我已将所有假期和周末都存储在名为nd<DateTime, string> 的字典中。键DateTime 有一系列日期,从2011-01-01 到2013-01-01,一步一步,值string 是TR 或NT,一个字符串变量但不是布尔值。如果是周末或节假日,则字符串为NT,否则为TR。
我想做的是当dDate 是周末或假期时,减去一天。比如dDate是2012-01-02是假期,把dDate改成2012-01-01,又因为是周末(Sunday),改成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);
}
}
}
【问题讨论】:
-
你在使用多线程吗?
-
你应该展示你是如何填充你的字典的。
-
是你所有的代码,还是中间缺少部分
-
您似乎在第一部分的检查和循环中都使用了
dDate,但在第二部分中,您在if和while检查中使用了dDate1,但您使用dDate2在数学中。这是故意的吗? -
我不确定您的整个逻辑是否有效,但这是不同的问题。如果您使用日期作为字典的键,通常不是一个好主意。显然,您试图找到此密钥,但“日期时间”是一种非常灵活的数据类型,您会遇到问题。使用字符串作为字典的键。
标签: c# dictionary key containskey