我想初始化一个string,datetime
字典,我希望每个字符串都有一个“实际”时间值。稍后我想将字符串作为键插入下拉列表,将日期时间作为值插入。
1 hour (string)- datetime(1 hour value)
5 hour (string)- datetime(5 hour value)
2 days (string)- datetime(2 days value)
3 weeks (string)-datetime(3 weeks value)
我如何制作这种字典?
public Dictionary<string,DateTime> TimeStep()
{
Dictionary<string,DateTime> timestep =
{ "1 Hour", "2 Hours", "5 Hours", "10 Hours", "15 Hours", "24 Hours", "Two Days", "Five Days", "Ten Days", "Two Weeks", "Month" };
return timestep ;
}
答案 0 :(得分:5)
var dic = new Dictionary<string, TimeSpan>()
{
{"1 Hour", TimeSpan.FromHours(1)},
{"Two days", TimeSpan.FromDays(2)}
};
答案 1 :(得分:2)
而不是DateTime
,您应该使用TimeSpan
Dictionary<string, TimeSpan> dictionary = new Dictionary<string, TimeSpan>();
dictionary.Add("1 hour", new TimeSpan(1, 0, 0)); //1 hour
dictionary.Add("2 days", new TimeSpan(2, 0, 0, 0));//2 days
答案 2 :(得分:0)
试试这个:
Dictionary<string, TimeSpan> testDictionary = new Dictionary<string, TimeSpan>()
{
{"1 hour", TimeSpan.FromHours(1) },
{"2 hour", TimeSpan.FromHours(2) },
{"3 hour", TimeSpan.FromHours(3) }
};
或使用添加字典方法,如下所示:
Dictionary<string, TimeSpan> testDictionary = new Dictionary<string, TimeSpan>();
testDictionary.Add("1 Hour", TimeSpan.FromHours(1));