I'm converting a project from Java to C#. I've tried to search this, but all I come across is questions about enums. There is a Hashtable htPlaylist, and the loop uses Enumeration to go through the keys. How would I convert this code to C#, but using a Dictionary instead of a Hashtable?
// 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());
}
Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can iterate the contents of an enumeration using for loop, using forEach loop and, using java.
Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.
We can convert an enum to string by calling the ToString() method of an Enum.
An enumeration (enum for short) in Java is a special data type which contains a set of predefined constants. You'll usually use an enum when dealing with values that aren't required to change, like days of the week, seasons of the year, colors, and so on.
Eh, just a foreach
loop? For the given
Dictionary<int, SongInfo> htPlaylist = MySongs.getSongs();
either
foreach (var pair in htPlaylist) {
// int key = pair.Key;
// SongInfo info = pair.Value;
...
}
or if you want just keys:
foreach (int key in htPlaylist.Keys) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With