2017-02-03 28 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) { 
    ... 
    }