Search code examples
c#sql-serverbitbit-fields

Reading a bitfield (used for Selected Days) and determining values from it in c#


I have a column of type int called SelectedDays in my database. I decided to go with the bit approach:

sun=1, mon=2, tue=4, wed=8, thu=16, fri=32, sat=64

If the user selects Sun, Mon, Wed then the value in the field would be 11

In my C# model I am trying to make a readonly property:

public List<string> Days

that will return a list of the selected days in string format.

I can't figure out how to go from 11 to "Sunday", "Monday", "Wednesday"


Solution

  • int valueFromDb = 11;
    var result = Enum.GetNames(typeof(WeekDays))
                     .Where(x => (valueFromDb & (int)Enum.Parse(typeof(WeekDays), x)) > 0)
                     .ToList();
    

    You can do it like this. Full example