Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16280

How to cast Enum with Description attribute to dictionary?

Based on this question, and preferably using this answer along with this answer to get enum attributes, how is it possible to cast the enum to a dictionary where Key is the enum value itself and Value is the description attribute?

Upvotes: 3

Views: 1536

Answers (1)

pierroz
pierroz

Reputation: 7870

Given the GetAttributeOfType<T>() extension method you can simply do:

var dic = Enum.GetValues(typeof(SomeEnum))
.Cast<SomeEnum>()
.ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>())

If you directly want the Description in the value:

var dic = Enum.GetValues(typeof(SomeEnum))
.Cast<SomeEnum>()
.ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>().Description)

Upvotes: 10

Related Questions