Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Enumeration<Integer> for loop from Java to C#? What exactly is an Enumeration<Integer> in C#? [duplicate]

Tags:

java

c#

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());
}
like image 358
Michael Weston Avatar asked Feb 03 '17 10:02

Michael Weston


People also ask

Can you loop through enum Java?

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.

How do I iterate over an enum?

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.

Can enum be converted to string?

We can convert an enum to string by calling the ToString() method of an Enum.

What is Java enumeration?

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.


1 Answers

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) {
     ...
   }
like image 152
Dmitry Bychenko Avatar answered Oct 05 '22 13:10

Dmitry Bychenko