Convert Enum to KeyValuePair List and remove unwanted Enum options #Linq

In our new project, using Angular, I needed to fill drop down lists in a form from a set of enums. One particular case was to set the below Status Enum as a drop down list.

[code language=”csharp”]
public enum Status
{
Deactive = 1,
Active = 2,
Expired = 3,
Deleted = 4,
}
[/code]

To do that, the best solution I found was to convert the enums to a list KeyValuePair items. How do you do that?

To convert the enum to a keyvalue pair list, first get the enum values and cast them to the enum type. Then use the .Select Linq function to change the Enum to a string for enum text and int for the value as follows:

[code language=”csharp”]
Enum.GetValues(typeof(Status)).Cast()
.Select(e =>
new KeyValuePair<string, int>(e.ToString(), (int)e))
);
[/code]

 

If you want to remove an enum option from the keyvalue pair list, use the .Where Linq function as follows:

[code language=”csharp”]
Enum.GetValues(typeof(Status)).Cast()
.Where(x => x != Status.Deleted)
.Select(e =>
new KeyValuePair<string, int>(e.ToString(), (int)e))
);
[/code]

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *