Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only the first value from a flags enum value and get it in the order they were added

Tags:

c#

I have the following code:

[Flags()]
public enum Foo
{
    Unknown = 0x00,
    A = 0x01,
    B = 0x02,
    C = 0x04,
    D = 0x08,
}

public static class Extensions
{
    public static List<Foo> AsList(this Foo types)
    {
        List<Foo> list = new List<Foo>();
        foreach(Foo sT in Enum.GetValues(typeof(Foo)))
        {
            if ((sT & types) == sT) list.Add(sT);
        }
        return list;
    }

}

class Program
{
    static void Main(string[] args)
    {
        Foo foo1 = Foo.A | Foo.B | Foo.C;
        Foo foo2 = Foo.C | Foo.B;

        Foo firstInfoo1 = foo1.AsList()[0];
        Foo firstInFoo2 = foo2.AsList()[0];
    }
}

Now firstInfoo1 and firstInfoo2 both come out be Unknown which i don't want. Seeing the code that is there should i return the index [1] always, as so : foo1.AsList()[1]?

Is that a good idea?? Any ideas on the error, bound checking that would need to be done.

Also lets have a look at foo2, i added Foo.C first and Foo.B second. Is there any way i can get from AsList Foo.C and not Foo.B, i.e. the first in order they were added.

Is that possible?

Appreciate the help.

Thanks

like image 617
Sourav 'Abhi' Mitra Avatar asked Oct 03 '22 07:10

Sourav 'Abhi' Mitra


1 Answers

Either remove the Unknown value, or do this:

if ((int)sT != 0 && (sT & types) == sT) list.Add(sT);

A little background: those OR-ed enums are not stored like that in memory, they are stored as a simple integer number, so .NET doesn't known how that enum was constructed.

like image 75
fejesjoco Avatar answered Oct 09 '22 19:10

fejesjoco