Domanda

Following is my code to convert enum values to Dictionary.

public static Dictionary<string, string> EnumToDictionary<T>() where T : struct, IConvertible
    {
        var oResult = new Dictionary<string, string>();
        if (typeof(T).IsEnum)
            foreach (T oItem in Enum.GetValues(typeof(T)))
                oResult.Add(oItem.ToString(), oItem.ToString());
        return oResult;
    }

and this is my enum

public enum MyEnum
{
    Value1,
    Value2,
    value3
}

Currently I am calling that method like

var result=EnumToDictionary<MyEnum>();

but I need to use that method like

var result=MyEnum.EnumToDictionary();

or any other way like string extension methods.

È stato utile?

Soluzione

In general your problem is connected with the fact that you want to create a generic extensions method (that's possible) but without any object reference sent as "this" parameter when calling such a method (that's not possible). So using extension methods is not an option to achieve what you want.

You could do sth like this:

public static Dictionary<string, string> EnumToDictionary(this Enum @enum)
{
    var type = @enum.GetType();
    return Enum.GetValues(type).Cast<string>().ToDictionary(e => e, e => Enum.GetName(type, e));
}

But this would mean that you need to operate on a certain instance of enum class to call such an extension method.

Or you could do this in such a way:

    public static IDictionary<string, string> EnumToDictionary(this Type t)
    {
        if (t == null) throw new NullReferenceException();
        if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");

        string[] names = Enum.GetNames(t);
        Array values = Enum.GetValues(t);

        return (from i in Enumerable.Range(0, names.Length)
                select new { Key = names[i], Value = (int)values.GetValue(i) })
                    .ToDictionary(k => k.Key, k => k.Value.ToString());
    }

And then call it like this:

var result = typeof(MyEnum).EnumToDictionary();

Altri suggerimenti

You could write an extension method, something like:

    public static IDictionary<string, string> ToDictionary(this Enum value)
    {
        var result = new Dictionary<string, string>();
            foreach (var item in Enum.GetValues(value.GetType()))
                result.Add(Convert.ToInt64(item).ToString(), item.ToString());
        return result;
    }

But to call such an extension method, you need to provide an instance of the required enum. E.g.

        var dict = default(System.DayOfWeek).ToDictionary();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top