3

I'm trying to get all the enum values from the Type enum variable :

[Flags]
    enum Type
    {
        XML = 1,
        HTML = 2,
        JSON = 4,
        CVS = 8
    }


static void Main(string[] args)
{

    Type type = Type.JSON | Type.XML;

    List<Type> types = new List<Type>();

    foreach (string elem in type.ToString().Split(',') )
        types.Add(  (Type)Enum.Parse( typeof(Type), elem.Trim() ) );          

}

Is there a better way to do that ?

Brahim Boulkriat
  • 956
  • 2
  • 8
  • 20
  • 2
    Answer: http://stackoverflow.com/questions/4171140/iterate-over-values-in-flags-enum –  Nov 21 '13 at 09:25

2 Answers2

6
List<Type> types = Enum
                     .GetValues(typeof(Type))
                     .Cast<Type>()
                     .Where(val => (val & type) == val)
                     .ToList();

Another way getting desired result.

Dmytro Rudenko
  • 2,454
  • 2
  • 11
  • 21
-1

Firstly try not to use the word 'Type' when naming the enum.Use EnumType or something else Use Enum.GetValues..something like this

public static List<EnumType> GetValues(Type enumType)
    {
        List<EnumType > enums = new List<EnumType >();
        if (!enumType.IsEnum) throw new ArgumentException(Enum type not found");

        foreach (EnumType value in Enum.GetValues(enumType))
            enums.Add(value);

        return enums;
    }
liquidsnake786
  • 439
  • 2
  • 8