mercu mercu - 2 months ago 5
C# Question

Get Enum Values from int

How can get the enum values from an int input?
Let's say I have this enum below.

[Flags]
public enum Weeks
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}

public List<Weeks> GetEnumValues(int input)
{
// Don't know what is the logic here
// Help is much appreciated
}


Then the output is as follows

Examples:
1.) input = 3; This means Sunday and Monday hence 1 + 2 = 3; This should return List<Weeks> { Sunday, Monday }
2.) input = 20; This means Tuesday and Thursday hence 4 + 16 = 20; This should return List<Weeks> { Tuesday, Thursday }
3.) input = 40; This means Wednesday and Friday hence 8 + 32 = 40; This should return List<Weeks> { Wednesday, Friday }


Thank you in advance.

Answer

You can do this by looping every enum "flag" and checking for each "flag" if the bit is set in your input value. Here is one way to do this:

public List<Weeks> GetEnumValues(int input)
{
    Weeks inputEnum = (Weeks)input;
    var list = new List<Weeks>();

    foreach(var enumFlag in Enum.GetValues(typeof(Weeks)).Cast<Weeks>())
    {
        if (inputEnum.HasFlag(enumFlag))
        {
            list.Add(enumFlag);
        }
    }

    return list;
}