C# 将带有[DescriptionAttribute]的枚举转换为字典<;字符串,int>;
我有这个枚举C# 将带有[DescriptionAttribute]的枚举转换为字典<;字符串,int>;,c#,dictionary,enums,C#,Dictionary,Enums,我有这个枚举 public enum Genders { [Description("Nữ")] Female, [Description("Nam")] Male } 我使用此代码获取每个枚举名称和值,并将其保存到字典中 结果是 女:0 男:1 accountViewModel.Genders = Enum.GetValues(typeof(Account.Genders))
public enum Genders
{
[Description("Nữ")]
Female,
[Description("Nam")]
Male
}
我使用此代码获取每个枚举名称和值,并将其保存到字典中
结果是
女:0
男:1
accountViewModel.Genders = Enum.GetValues(typeof(Account.Genders))
.Cast<Account.Genders>()
.ToDictionary(t => t.ToString(), t => (int)t);
accountViewModel.Genders=Enum.GetValues(typeof(Account.Genders))
.Cast()
.ToDictionary(t=>t.ToString(),t=>(int)t);
如何修改上述代码以获得每个枚举的描述和值
像这样
Nữ : 0
Nam:1根据回答
其中value
是int
enum值
您可以使用以下内容:
accountViewModel.Genders = Enum.GetValues(typeof(Account.Genders))
.Cast<Account.Genders>()
.ToDictionary(t => Enumerations.GetEnumDescription((Genders)t), t => (int)t);
accountViewModel.Genders=Enum.GetValues(typeof(Account.Genders))
.Cast()
.ToDictionary(t=>Enumerations.GetEnumDescription((性别)t),t=>(int)t);
accountViewModel.Genders = Enum.GetValues(typeof(Account.Genders))
.Cast<Account.Genders>()
.ToDictionary(t => Enumerations.GetEnumDescription((Genders)t), t => (int)t);