I know how to loop through enum list of properties, but how would I loop through all "selected" enum properties? For example, if one did Prop1 | Prop2
against public enum Foo { Prop1; Prop2; Prop3 }
, how would I achieve this?
This is what I have now:
var values = Enum.GetValues(typeof(FileStatus)).Cast<FileStatus>();
foreach (var value in values)
{
}
It loops through all enum properties, but I'd like to loop only the ones that were "selected".
Update: [Flags]
attribute was set.
Update 2: The enum contains a large number of properties, I can't and won't type/hardcode a single property check, instead I want to dynamically loop through each of them and check if my enum instance Bar
contains the looped item set.
[Flags]
public enum Foo
{
Prop1 = 1,
Prop2 = 1 << 1,
Prop3 = 1 << 2
}
public static class FooExtensions
{
private static readonly Foo[] values = (Foo[])Enum.GetValues(typeof(Foo));
public static IEnumerable<Foo> GetComponents(this Foo value)
{
return values.Where(v => (v & value) != 0);
}
}
public static class Program
{
public static void Main(string[] args)
{
var foo = Foo.Prop1 | Foo.Prop3;
var components = foo.GetComponents().ToArray();
}
}
How about the following:
FileStatus status = FileStatus.New|FileStatus.Amazing;
foreach (FileStatus x in Enum.GetValues(typeof(FileStatus)))
{
if (status.HasFlag(x)) Console.WriteLine("{0} set", x);
}
Or in one fell LINQ swoop:
var flags = Enum.GetValues(typeof(FileStatus))
.Cast<FileStatus>()
.Where(s => status.HasFlag(s));
Assuming you have this set as a bitmask, then simply "and"-ing the values would determine which are selected.
SomeEnum bitmask = value;
if(bitmask & SomeEnum.Value1 > 0)
// SomeEnum.Value1 was set
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With