-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 ;        
    }
4

3 回答 3

5
var dic = new Dictionary<string, TimeSpan>()
          {
                {"1  Hour", TimeSpan.FromHours(1)},
                {"Two days", TimeSpan.FromDays(2)}
          };
于 2013-02-28T06:27:01.653 回答
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
于 2013-02-28T06:25:55.810 回答
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 的Add方法,如下所示:

Dictionary<string, TimeSpan> testDictionary = new Dictionary<string, TimeSpan>();
testDictionary.Add("1 Hour", TimeSpan.FromHours(1));
于 2013-02-28T06:32:56.667 回答