class="csharpcode"> /// <summary> /// dic.Keys.ToArray<>方法生成数组的顺序和dic中的顺序相同 /// </summary> public static void TestDicToArray() { Dictionary<DateTime, string> dic = new Dictionary<DateTime, string>(); DateTime dt1 = DateTime.Parse("2013-9-29"); int day = dt1.Day; DateTime dtTemp; for (int i = 1; i < day; i++) { dtTemp=dt1.AddDays(-i); dic.Add(dtTemp, dtTemp.ToShortDateString()); } foreach (KeyValuePair<DateTime, string> kvp in dic) { Console.WriteLine(string.Format("{0} {1}", kvp.Key.ToShortDateString(),kvp.Value)); } DateTime[] dtKeys=dic.Keys.ToArray<DateTime>(); Console.WriteLine("======================="); for (int i = 0; i < dtKeys.Length; i++) { Console.WriteLine(string.Format("{0}==>{1}", i, dtKeys[i].ToShortDateString())); } Console.ReadLine(); }
output:
2013/9/28 2013/9/28
2013/9/27 2013/9/27
2013/9/26 2013/9/26
2013/9/25 2013/9/25
2013/9/24 2013/9/24
2013/9/23 2013/9/23
2013/9/22 2013/9/22
2013/9/21 2013/9/21
2013/9/20 2013/9/20
2013/9/19 2013/9/19
2013/9/18 2013/9/18
2013/9/17 2013/9/17
2013/9/16 2013/9/16
2013/9/15 2013/9/15
2013/9/14 2013/9/14
2013/9/13 2013/9/13
2013/9/12 2013/9/12
2013/9/11 2013/9/11
2013/9/10 2013/9/10
2013/9/9 2013/9/9
2013/9/8 2013/9/8
2013/9/7 2013/9/7
2013/9/6 2013/9/6
2013/9/5 2013/9/5
2013/9/4 2013/9/4
2013/9/3 2013/9/3
2013/9/2 2013/9/2
2013/9/1 2013/9/1
=======================
0==>2013/9/28
1==>2013/9/27
2==>2013/9/26
3==>2013/9/25
4==>2013/9/24
5==>2013/9/23
6==>2013/9/22
7==>2013/9/21
8==>2013/9/20
9==>2013/9/19
10==>2013/9/18
11==>2013/9/17
12==>2013/9/16
13==>2013/9/15
14==>2013/9/14
15==>2013/9/13
16==>2013/9/12
17==>2013/9/11
18==>2013/9/10
19==>2013/9/9
20==>2013/9/8
21==>2013/9/7
22==>2013/9/6
23==>2013/9/5
24==>2013/9/4
25==>2013/9/3
26==>2013/9/2
27==>2013/9/1