Created
August 5, 2025 12:23
-
-
Save DavidRogersDev/349923f24498619130f1f5184685f1c1 to your computer and use it in GitHub Desktop.
Get the Flags from an Enum as an Enumerable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// This method retrieves all of the flags for a particular enum, and returns it as an enumerable. | |
/// </summary> | |
private static IEnumerable<Enum> GetFlags(Enum value, Enum[] values) | |
{ | |
ulong bits = Convert.ToUInt64(value); | |
List<Enum> results = new List<Enum>(); | |
for (int i = values.Length - 1; i >= 0; i--) | |
{ | |
ulong mask = Convert.ToUInt64(values[i]); | |
if (i == 0 && mask == 0L) | |
{ | |
break; | |
} | |
if ((bits & mask) == mask) | |
{ | |
results.Add(values[i]); | |
bits -= mask; | |
} | |
} | |
if (bits != 0L) | |
return Enumerable.Empty<Enum>(); | |
if (Convert.ToUInt64(value) != 0L) | |
return results.Reverse<Enum>(); | |
if (bits == Convert.ToUInt64(value) && values.Length > 0 && Convert.ToUInt64(values[0]) == 0L) | |
return values.Take(1); | |
return Enumerable.Empty<Enum>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment