2017-02-03 27 views
2

我正在將一個項目從Java轉換爲C#。我試圖搜索這個,但我遇到的只是有關枚舉的問題。有一個Hashtable htPlaylist,循環使用Enumeration通過鍵。如何將此代碼轉換爲C#,但使用字典而不是哈希表?轉換枚舉<Integer> for循環從Java到C#?枚舉<Integer>在C#中究竟是什麼?

// My C# Dictionary, formerly a Java Hashtable. 
Dictionary<int, SongInfo> htPlaylist = MySongs.getSongs(); 

// Original Java code trying to convert to C# using a Dictionary. 
for(Enumeration<Integer> e = htPlaylist.keys(); e.hasMoreElements(); 
{ 
    // What would nextElement() be in a Dictonary? 
    SongInfo popularSongs = htPlaylist.get(e.nextElement()); 
} 
+2

哎呀,怎麼老這是Java代碼? –

+1

[在C#中迭代字典的最佳方式是什麼?](http://stackoverflow.com/questions/141088/what-is-the-best-way-to-iterate-over-a-dictionary-in -c) – Equalsk

+0

所以我應該做foreach(KeyValuePair ?雖然在Java中Enumeration 究竟是什麼?在C#中等價於什麼? –

回答

4

呃,只是一個foreach循環?對於給定的

Dictionary<int, SongInfo> htPlaylist = MySongs.getSongs(); 

要麼

foreach (var pair in htPlaylist) { 
    // int key = pair.Key; 
    // SongInfo info = pair.Value; 
    ... 
    } 

,或者如果你只想鍵:

foreach (int key in htPlaylist.Keys) { 
    ... 
    }