EnumParser - mojtabanabavi/Loby.AspNetCore GitHub Wiki

About

Provide capability to convert enums to some other types.

Namespace

Loby.AspNetCore.Helpers

Enum sample

Our enum for all sample codes is defined below that contains 7 fields called days of the week and for each one of them a number from 1 to 7 is assigned respectively. A description is also provided for each of them by System.ComponentModel.DescriptionAttribute.Description.

enum DayOfWeek
{
    [Description("First day of the week.")]
    Monday = 1,

    [Description("Second day of the week.")]
    Tuesday = 2,

    [Description("Third day of the week.")]
    Wednesday = 3,

    [Description("Fourth day of the week.")]
    Thursday = 4,

    [Description("Fifth day of the week.")]
    Friday = 5,

    [Description("Sixth day of the week.")]
    Saturday = 6,

    [Description("Seventh day of the week.")]
    Sunday = 7,
}

Convert enum to select list

Since enums are constant and they are commonly used on web pages as select list (Microsoft.AspNetCore.Mvc.Rendering.SelectList), its essential to have some functions to do this conversion. These functions are:

SelectList ToSelectList<T>();
SelectList ToSelectList<T>(object selectedValue);

A simple conversion would be like:

SelectList DayOfWeekSelectList = EnumParser.ToSelectList<DayOfWeek>();

This function returns a new instance of Microsoft.AspNetCore.Mvc.Rendering.SelectList that is created based on enum type T which the select list item value is the number assigned to each enum field and the text is System.ComponentModel.DescriptionAttribute.Description, if it's defined; otherwise the name of enum field.

In most case we have a default selected item in select list. it can be set using another override of this function. See the below sample:

SelectList DayOfWeekSelectList = EnumParser.ToSelectList<DayOfWeek>(selectedValue: 4);

Convert enum to dictionary

Since enums are constant and in some situations we like to have them as dictionary (System.Collections.Generic.Dictionary), this can be easily done by using following function.

Dictionary<int, string> ToDictionary<T>();

This function returns a new instance of System.Collections.Generic.Dictionary that is created based on enum type T which the keys are the number assigned to each field and the values are System.ComponentModel.DescriptionAttribute.Description, if it's defined; otherwise the name of enum field.

A simple conversion would be like:

Dictionary<int, string> DayOfWeekDictionary = EnumParser.ToDictionary<DayOfWeek>();
⚠️ **GitHub.com Fallback** ⚠️