Home > Blockchain >  bitwise logical operator on enum list
bitwise logical operator on enum list

Time:11-09

I have a an enum WeekDays, with Flag attribute on top,

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

I want to use this enum as a list in another model. The issue I am facing is while mapping a list of enum from FE to map to an int variable to store in database column. I'm not sure how to do it. what I was trying so far i:

int daysBit;
var settings = await _globalContext.settingsModel.SingleOrDefaultAsync(x => x.id == request.id);
if (adminEmailSettingsFromDb == null)
{
    foreach (var day in request.DaysOfWeek)
    {
        daysBit |= (day)WeekDays;
    }
    var exampleVariable = new settingsModel
    {
        DaysOfWeek = daysBit,
        CreatedAt = DateTime.UtcNow,
        UpdatedAt = DateTime.UtcNow
    };
}

CodePudding user response:

You could use Linq Aggregate to make a one-liner:

var dayBit = request.DaysOfWeek.Aggregate(WeekDays.None, (a, b) => a|b);

And the reverse:

public static IEnumerable<WeekDays> GetFlagList(WeekDays days)
{
    var all = (WeekDays[])Enum.GetValues(typeof(WeekDays));

    foreach (var value in all)
    {
        if ((days & value) == value)
        {
            yield return value;
        }
    }
}

CodePudding user response:

So all I did to fix this was, in the same above code


WeekDays daysBit=WeekDays.None;
foreach (var day in request.DaysOfWeek)
{
    daysBit |= day;
}

just updated these two lines.

  • Related