How to write an extension that calculates bitmask from a given list of enums

Viewed 34

I have an enum

public enum MyEnum{
   None =0,
   First = 1,
   Second = 2,
   Thirds = 4
}

I have a list of these enums

List<MyEnum> MyEnumList;

I would like to get a bitmask result of MyEnum selection as

int bitMask = Enum.GetBitMask<MyEnum>(MyEnumList);
1 Answers

Here is my solution, I could not find anything more elegant yet.

public static class EnumExtensions
{
    public static int GetBitmask<T>(List<T> collection)
    {
        if (!collection?.Any() ?? true)
            return 0;
        int output = Convert.ToInt32(collection.First());
        collection.ForEach(x => output |= Convert.ToInt32(x));
        return output;
    }
} 

Here is how you would call it

int bitMask = EnumExtensions.GetBitmask(MyEnumList);
Related