Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through "selected" Enum values? [duplicate]

Tags:

c#

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.

like image 704
Tower Avatar asked Apr 24 '12 17:04

Tower


3 Answers

[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();
    }
}
like image 188
Stipo Avatar answered Nov 02 '22 00:11

Stipo


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));
like image 36
user7116 Avatar answered Nov 02 '22 00:11

user7116


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
like image 3
Tejs Avatar answered Nov 02 '22 01:11

Tejs