如何初始化这本词典

我想初始化一个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 TimeStep() { Dictionary timestep = { "1 Hour", "2 Hours", "5 Hours", "10 Hours", "15 Hours", "24 Hours", "Two Days", "Five Days", "Ten Days", "Two Weeks", "Month" }; return timestep ; } 

 var dic = new Dictionary() { {"1 Hour", TimeSpan.FromHours(1)}, {"Two days", TimeSpan.FromDays(2)} }; 

而不是DateTime你应该使用TimeSpan

 Dictionary dictionary = new Dictionary(); dictionary.Add("1 hour", new TimeSpan(1, 0, 0)); //1 hour dictionary.Add("2 days", new TimeSpan(2, 0, 0, 0));//2 days 

试试这个:

 Dictionary testDictionary = new Dictionary() { {"1 hour", TimeSpan.FromHours(1) }, {"2 hour", TimeSpan.FromHours(2) }, {"3 hour", TimeSpan.FromHours(3) } }; 

或者使用Dictionary的Add方法如下:

 Dictionary testDictionary = new Dictionary(); testDictionary.Add("1 Hour", TimeSpan.FromHours(1));