【发布时间】:2017-02-22 00:31:34
【问题描述】:
我定义了一个从 Dictionary 继承的名为 Diversion 的新类,用于保存一组 DateTime 键和相关的 int 值。
我想返回最早的键值和平均 int 值作为类的属性(假设它已被填充)。
有没有更有效的方法来遍历字典?定义类的实例时如何引用它?
提前感谢所有帮助!
public class Diversion : Dictionary<DateTime, int>
{
private DateTime _starttime;
private decimal _avg;
public DateTime Starttime {
get {
if (Diversion.count > 0) {
_starttime = new DateTime(2999,1,1);
foreach(KeyValuePair<DateTime, int> de in Diversion) {
if (de.key < _starttime) _starttime = de.key;
}
return _starttime;
}
else return;
}
}
public DateTime AvgVal {
get {
if (Diversion.count > 0) {
_avg = 0;
foreach(KeyValuePair<DateTime, int> de in Diversion) {
_avg = _avg + de.value;
}
_avg = _avg / Diversion.count;
return _avg;
}
else return;
}
}
public Diversion() {}
}
【问题讨论】:
-
this是你的朋友 -
为什么不在字典被操纵时跟踪这些东西,而不是在需要时计算它们
标签: c#