Iterating Over Values of an Enum with Flags
Question:
When working with an enum that supports flags, how can one iterate specifically over the individual, single-bit values that are set in a particular variable? Is it possible to avoid iterating over the entire enum using Enum.GetValues?
Answer:
Yes, it's possible to iterate over the individual flag values in an enum variable without the need to enumerate the entire enum and check if the values are set. This can be achieved using the following code snippet:
static IEnumerable<Enum> GetFlags(Enum input) { foreach (Enum value in Enum.GetValues(input.GetType())) if (input.HasFlag(value)) yield return value; }
Explanation:
By using this approach, you can efficiently iterate over the individual flag values of the enum variable.
The above is the detailed content of How to Iterate Over Only the Set Flags in a C# Enum?. For more information, please follow other related articles on the PHP Chinese website!