Brief
Convert enum to dictionary.- CustomEnum enum
- Extension class
- Program class
CustomEnum
public enum CustomEnum
{
New = 2,
Old,
Active,
InActive,
Expired
}
{
New = 2,
Old,
Active,
InActive,
Expired
}
Extension Class
public static class Extension
{
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this Type e)
{
var dictionary = new Dictionary<TKey, TValue>();
if (e.IsEnum)
{
var array = e.GetEnumValues();
foreach (var t in array)
{
dictionary.Add((TKey)t, (TValue)t);
}
}
{
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this Type e)
{
var dictionary = new Dictionary<TKey, TValue>();
if (e.IsEnum)
{
var array = e.GetEnumValues();
foreach (var t in array)
{
dictionary.Add((TKey)t, (TValue)t);
}
}
return dictionary;
}
}
}
}
Program Class
class Program
{
static void Main(string[] args)
{
var dictionary = typeof(CustomEnum).ToDictionary<int, CustomEnum>();
var dictionaryReverse = typeof(CustomEnum).ToDictionary<CustomEnum, int>();
Console.ReadKey();
}
}
{
static void Main(string[] args)
{
var dictionary = typeof(CustomEnum).ToDictionary<int, CustomEnum>();
var dictionaryReverse = typeof(CustomEnum).ToDictionary<CustomEnum, int>();
Console.ReadKey();
}
}
Comments
Post a Comment