0

Possible Duplicate:
Iterating through an enumeration in Silverlight?

Is there a way to iterate through all values in an Enum in Silverlight with C#?

I know WPF allows you to use the System.Enum.GetType(Type) method, but this is not available in Silverlight.

Thanks, Seth

Community
  • 1
  • 1
Britt Wescott
  • 568
  • 1
  • 9
  • 28

2 Answers2

4
    public static IEnumerable<T> GetEnumValues<T>()
    {
        return typeof(T)
            .GetFields()
            .Where(x => x.IsLiteral)
            .Select(field => (T)field.GetValue(null));
    }

usage

        foreach (var bindingFlag in GetEnumValues<BindingFlags>())
        {
            Debug.WriteLine(bindingFlag);
        }
Simon
  • 33,714
  • 21
  • 133
  • 202
0

Try this:

    public static List<T> GetList<T>(Type enumType)
    {
        List<T> output = new List<T>();

        var fields = from field in enumType.GetFields()
                     where field.IsLiteral
                     select field;


        foreach (FieldInfo field in fields)
        {
            object value = field.GetValue(enumType);
            output.Add((T) value);
        }

        return output;

    }

Call it like this:

List<MyEnum> myList = GetList<MyEnum>(typeof(MyEnum))
slugster
  • 49,403
  • 14
  • 95
  • 145