Create a list of enumerations and pass them to the method

I created a method that takes an enumeration and converts it to a dictionary, where each int is associated with the name (as a string) of the enumeration

// Define like this
public static Dictionary<int, string> getDictionaryFromEnum<T>()
{
   List<T> commandList = Enum.GetValues(typeof(T)).Cast<T>().ToList();
   Dictionary<int, string> finalList = new Dictionary<int, string>();
   foreach (T command in commandList)
   {
    finalList.Add((int)(object)command, command.ToString());
   }
 return finalList;
 }

(ps. yes, I have a double click, but the application is for very cheap and dirty C # -enum for Javascript-enum converter).

It can be easily used like this.

private enum _myEnum1 { one = 1001, two = 1002 };
private enum _myEnum2 { one = 2001, two = 2002 };
// ... 
var a = getDictionaryFromEnum<_myEnum1>();
var b = getDictionaryFromEnum<_myEnum2>();

Now I was wondering if I could create an enumeration list to use for a series of calls to iterate my calls.

That was in the original question: [Why can't I call it?]

What should I do to create a challenge like this?

List<Type> enumsToConvertList = new List<Type>();
enumsToConvertList.Add(typeof(_myEnum1));
enumsToConvertList.Add(typeof(_myEnum2));
// this'll be a loop
var a = getDictionaryFromEnum<enumsToConvertList.ElementAt(0)>();
+5
source share
5 answers

(, ). , - , Type type:

public static Dictionary<int, string> getDictionaryFromEnum(Type enumType)
{
    return Enum.GetValues(enumType).Cast<object>()
               .ToDictionary(x => (int)x, x => x.ToString());
}

:

List<Type> enumsToConvertList = new List<Type>();
enumsToConvertList.Add(typeof(_myEnum1));
enumsToConvertList.Add(typeof(_myEnum2));

var a = getDictionaryFromEnum(enumsToConvertList[0]);
+6

?

System.Type, generic, .

+2

.

System.Type , .


, , , Dictionary<int, string>. Type , @lazyberezovsky.

0

:

List<Type> enumsToConvertList = new List<Type>();
enumsToConvertList.Add(_myEnum1);
var a = getDictionaryFromEnum<typeof(enumsToConvertList.ElementAt(0))>();
0

, Enum

 public static Dictionary<int, string> ToDictionary<T>()
    {
        var type = typeof (T);
        if (!type.IsEnum) throw new ArgumentException("Only Enum types allowed");
        return Enum.GetValues(type).Cast<Enum>().ToDictionary(value => (int) Enum.Parse(type, value.ToString()), value => value.ToString());
    }
0

All Articles