Reputation: 3491
I try to convert an enum to Dictionary int is the value and string is the description of the value.
I already have a function that gets the enum description by it's value but I don't how to use it with the enum iteration I have:
public static IDictionary<int, string> ConvertEnumToDictionary<K>()
{
Dictionary<int, string> mydic = new Dictionary<int, string>();
foreach (K foo in Enum.GetValues(typeof(K)))
{
//???
mydic.Add((int)foo, GetEnumDescription(foo));
}
}
public static string GetEnumDescription(Enum value)
{
// Get the Description attribute value for the enum value
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
public enum Lu_LanguageTypes
{
[Description("Hebrew")]
he = 1,
[Description("Englishj")]
en = 2,
[Description("Spanish")]
es = 3
}
Upvotes: 1
Views: 196
Reputation: 23298
You can modify ConvertEnumToDictionary
method a little bit and apply where K : Enum
generic constraint (available from C# 7.3) and cast Enum
value to K
before passing to GetEnumDescription
method
public static IDictionary<int, string> ConvertEnumToDictionary<K>() where K : Enum
{
var mydic = new Dictionary<int, string>();
foreach (var foo in Enum.GetValues(typeof(K)))
{
mydic.Add((int)foo, GetEnumDescription((K)foo));
}
return mydic;
}
Example of the usage, which gives a dictionary with 3 key-value pairs
var result = ConvertEnumToDictionary<Lu_LanguageTypes>();
Another option is to add constraint to IConvertible
interface as well (since Enum
type implements it) and avoid casting
public static IDictionary<int, string> ConvertEnumToDictionary<K>() where K : Enum, IConvertible
{
var mydic = new Dictionary<int, string>();
foreach (K foo in Enum.GetValues(typeof(K)))
{
mydic.Add(foo.ToInt32(null), GetEnumDescription(foo));
}
return mydic;
}
Upvotes: 2