Here is an Ani answer option:
public static void MyMethod(Flags flag) { // Define action-lookup var dict = new Dictionary<Flags, Action> { { Flags.p1, DoSomething}, { Flags.p2, DosomethingElse}, { Flags.p3, DosomethingElseAgain}, { Flags.p4, DosomethingElseAgainAndAgain}, }; // Find applicable actions var actions = from value in Enum.GetValues(typeof(Flags)) where flag.HasFlag(value) select dict[value]; //Execute applicable actions foreach (var action in actions) action(); }
An important difference here is that it iterates over certain values ββin an enumeration, rather than entries in a dictionary. Thus, if you add a new flag to the enumeration without adding it to the dictionary, you will get an exception when you try to use the new flag. And it always iterates in order of flags.
Gabe
source share