Quantcast
Channel: Clive Ciappara - Developer for Apps & Websites » Quickie
Viewing all articles
Browse latest Browse all 13

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

$
0
0

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.

    public enum Status
    {
        Deactive = 1,
        Active = 2,
        Expired = 3,
        Deleted = 4,
    }

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:

    Enum.GetValues(typeof(Status)).Cast()
        .Select(e =>
            new KeyValuePair<string, int>(e.ToString(), (int)e))
    );

 

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

    Enum.GetValues(typeof(Status)).Cast()
        .Where(x => x != Status.Deleted)
        .Select(e =>
            new KeyValuePair<string, int>(e.ToString(), (int)e))
    );

Viewing all articles
Browse latest Browse all 13

Trending Articles