I have a method that converts a bitmask to a list of days using an Enum. I am trying to do the reverse, but am having trouble. I have DaysOfWeekToEnum working, but not DaysOfWeekFromEnum. Below is what I am trying to do. Can anyone help?
public static short DaysOfWeekFromEnum(IEnumerable<DaysInWeekIds> daysOfWeek)
{
short mask;
foreach (var item in daysOfWeek)
{
mask &= item; // ????
}
return mask
}
public static IEnumerable<DaysInWeekIds> DaysOfWeekToEnum(short mask)
{
var values = new List<DaysInWeekIds>();
foreach (short enumValue in Enum.GetValues(typeof(DaysInWeekIds)))
{
if (mask & enumValue == enumValue)
{
values.Add((DaysInWeekIds) Enum.ToObject(typeof(DaysInWeekIds),
enumValue));
}
}
return values;
}
/// <summary> The days in week ids. </summary>
public enum DaysInWeekIds : short
{
M = 1,
Tu = 2,
W = 4,
Th = 8,
F = 16,
Sa = 32,
Su = 64
}
It should be
|=, not&=, to set the additional bits.You could also join string representations together, and pass the result to
Enum.Parsemethod. This is not as efficient, but the code will look shorter.This returns
25for{M, Th, F}(link to ideone).