Search code examples
c#enumsflagsenum-flags

Write multiple list enum values into another enum


From the client I get a List where each int value is the enum int value of the Enum DayOfWeek.

The list contains only those int values (days) which are visible in a time planner.

Taking the list of int values e.g. 0,1,2 (sunday,monday,tuesday) how would you write those values into the DayOfWeek enum in a general way working for all 7 days or no day?

Just know that the Saturday has an index of 6 while my DayOfWeek enum has 32 as value.

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

UPDATE

This is the working solution code from MarcinJuraszek which is just changed to my needs:

var visibleWeekDays = new List<int>();
            for (int i = 0; i <= 6; i++)
            {
                visibleWeekDays.Add(i);
            }

            int allBitValues = visibleWeekDays.Select(i => (int)Math.Pow(2, ((i + 6) % 7))).Aggregate((e, i) => e | i);
            AllVisibleDays = (VisibleDayOfWeek) allBitValues;


[Flags]
public enum VisibleDayOfWeek
{
    None = 0,
    Mon = 1, 
    Tue = 2,
    Wed = 4,
    Thu = 8,
    Fri = 16,
    Sat = 32,
    Sun = 64
}


 public VisibleDayOfWeek AllVisibleDays { get; set; }

The above code writes all days of a week into the VisibleDayOfWeek enum which could be easily saved now in a database field.

According to Microsoft MSDN the flag enum has its None value now set to 0 again and the rest values are the power of 2.


Solution

  • var input = new List<int>() { 0, 1, 2 };
    
    var output = input.Select(i => (DayOfWeek)Math.Pow(2, ((i + 6) % 7))).ToList();
    

    That strange ((i + 6) % 7) is necessary because standard DayOfWeek starts from Sunday, and yours has 64 as a value for Sunday.

    You can use LINQ also to aggregate flags into single int value:

    var x = output.Select(i => (int)i).Aggregate((e, i) => e | i);
    

    Update

    For changed flags you have to change translation query:

    var output = input.Select(i => (DayOfWeek)Math.Pow(2, (i - 1) % 7)).ToList();