2013-02-28 112 views
-1

我想初始化一個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

您嘗試過搜索嗎?字面字典的語法看起來像是我可以很快找到的東西。 – Riking 2013-02-28 06:26:01

回答

5
var dic = new Dictionary<string, TimeSpan>() 
      { 
       {"1 Hour", TimeSpan.FromHours(1)}, 
       {"Two days", TimeSpan.FromDays(2)} 
      }; 
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 
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));