Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast Enum with Description attribute to dictionary?

Tags:

c#

enums

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?

like image 455
Ivan-Mark Debono Avatar asked Dec 09 '25 06:12

Ivan-Mark Debono


1 Answers

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)
like image 74
pierroz Avatar answered Dec 10 '25 18:12

pierroz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!