Reputation: 131
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.
Upvotes: 1
Views: 3138
Reputation: 131
@sstan's answer is correct and I voted as answer. But I just want to share also my short version from his solution.
public List<Weeks> GetEnumValues(int input)
{
Weeks inputEnum = (Weeks)input;
return Enum.GetValues(typeof(Weeks)).Cast<Weeks>().Where(x => inputEnum.HasFlag(x)).ToList();
}
Upvotes: 1
Reputation: 116
Another approach - making use of the fact that ToString on a Flags enum builds a comma separated list of the values. Then we can take that and convert each element back to the enum value via Enum.Parse:
public List<Weeks> GetEnumValues(int input)
{
return ((Weeks)input)
.ToString()
.Split(',')
.Select(day => Enum.Parse(typeof(Weeks), day))
.ToList();
}
The choice is yours...
Upvotes: 0
Reputation: 36483
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;
}
Upvotes: 4