Iterate through enum in Silverlight 4 [duplicate]
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
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);
}
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))
精彩评论