Last active
December 3, 2018 11:53
-
-
Save pedrovasconcellos/166527a43b407f1359a0517c7e9de2bc to your computer and use it in GitHub Desktop.
EnumToDictonary [int, string]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Programmed in LINQPad 5 | |
void Main() | |
{ | |
var result = EnumExtension.EnumToDictonary<CivilStatusEnum>(); | |
Console.WriteLine(result); | |
} | |
public static class EnumExtension | |
{ | |
public static Dictionary<int, string> EnumToDictionary<T>() where T : struct | |
{ | |
if (!typeof(T).IsEnum) throw new ArgumentException($"{typeof(T)} is not an Enum type"); | |
var dic = new Dictionary<int, string>(); | |
var enums = Enum.GetValues(typeof(T)); | |
foreach (var enumItem in enums) | |
{ | |
dic.Add((int)enumItem, enumItem.ToString()); | |
} | |
return dic; | |
} | |
public static IList<EnumeratorModel> EnumToModelList<T>() where T : struct | |
{ | |
if (!typeof(T).IsEnum) throw new ArgumentException($"{typeof(T)} is not an Enum type"); | |
var enumerators = new List<EnumeratorModel>(); | |
var enums = Enum.GetValues(typeof(T)); | |
foreach (var enumItem in enums) | |
{ | |
enumerators.Add(new EnumeratorModel() | |
{ | |
Id = (int)enumItem, | |
Name = enumItem.ToString() | |
}); | |
} | |
return enumerators; | |
} | |
} | |
public class EnumeratorModel | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
public enum CivilStatusEnum | |
{ | |
Divorced = 11, | |
Single = 9, | |
Married = 68, | |
Widowed = 22 | |
} | |
//Result | |
//[Key][Value] | |
//9 Single | |
//11 Divorced | |
//22 Widowed | |
//68 Married |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment