【发布时间】:2018-04-13 00:13:24
【问题描述】:
我有一个需要由排序字典初始化的数组。该数组将包含已在字典中修改的整数值。该数组的目的是包含在特定日期完成的提交。使用排序后的字典,我将 DateTime 作为键,将整数作为值。
//Array of integers which contains the number of commits that have been done on a particular day
protected int[] Values;
//Initializing a new SortedDictionary
private SortedDictionary<DateTime, int> Sorted = new SortedDictionary<DateTime, int>();
现在我用天(需要完成分配的时间段)和每天的起始整数值“0”(在类构造函数内部)填充排序字典。
//Fill Sorted dictionary with days and starting 0 value (inside class constructor)
for (DateTime date = assignment.Start; date < assignment.End ; date = date.AddDays(1))
{
Sorted.Add(date, 0);
}
接下来,我有几个来自 CommitInfo 类的提交。这些提交包含一个字段 TimeStamp,它是一个“日期时间”值。此提交的日期必须与排序字典中的 DateTime 键进行比较。如果日期相等,则字典中特定键的值需要加 1。
//Go through all the CommitInfo values
foreach(CommitInfo dates in commits)
{
//For every CommitInfo value go through all of the Keypairs inside the dictionary
foreach(KeyValuePair<DateTime, int> kvp in Sorted)
{
//If the dates are the same, increment by 1.
if (Sorted.ContainsKey(dates.TimeStamp.Date))
{
Sorted[kvp.Key] += 1;
}
}
}
现在这里可能出错了。字典包含应有的日期,但是当提交日期与字典中的日期相同时,每天的整数“0”值不会增加。我也尝试过这种 if 结构,但它也不起作用:
if (dates.TimeStamp.Date == kvp.Key)
{
Sorted[kvp.Key] += 1;
}
为了提供完整的信息,因为它可能在其他地方出错(即使我进行了调试),下一步是初始化并填充“值”数组。使用以下代码完成:
Values = new int[Sorted.Count];
Values = Sorted.Values.ToArray();
有人可以帮助我如何让它正常工作吗?因为我尝试了很多东西,但都没有奏效。
【问题讨论】:
-
您确定要跳入 if 语句吗?您只使用密钥检查 dates.TimeStamp 的日期部分。有你的任务。开始一个时间段?如果是这样,那么您的密钥也是如此,并且该语句将是错误的。
-
尝试
Sorted.Add(date.Date, 0);以确保您没有比较时间组件。 -
@Link 我 99% 确定问题出在 if 结构中。但是当我执行 'assignment.Start.Date' 或 Sorted.Add(date.Date, 0) 或 'kvp.Key.Date 我得到一个 InvalidOperationException。
-
@Lor 你能提供一个minimal, verifiable and complete example吗?这会更容易理解。
-
@Link 我已经解决了这个问题。我会发布答案:) 无论如何感谢您的帮助!
标签: c# datetime dictionary compare commit