We often use an Enum in C# to define all options for a field, such as a category Enum:
And we need a dropdown list for this category field. How would you implement this?
Basic
First, we get all values of CategoryEnum:
Then, we generate all select items for these values:
Here we use Cast<CategoryEnum>()
to cast all the values so we can apply Select method on them.
Finally, we have our dropdown list:
Custom Text
We can add descriptions to CategoryEnum and use them as the text value of each select list item.
We then get the description with Attribute.GetCustomAttribute method.
`
The updated code for the dropdown list would be:
Option Group
Sometimes we only want to display a subset of the Enum. We can define a static class for this so it can be shared everywhere.
Then we can filter them with Where method.
Final dropdown list code: