Today I came across a situation where iterating through an Enum would save me about 10 lines of code and some time. The quickest way is as follows:
foreach (MyEnum value in Enum.GetValues(typeof(MyEnum))){ //...}
foreach
Smart idea;-)
Notice what happens when your enum has [FlagsAttribute] on it. This may not be the behavior you want.
nice and quikest way to iterate enumeration
I am doing this to avoid any casts:
public static IEnumerable<TEnum> EnumAsEnumerable<TEnum>()
{
var enumType = typeof(TEnum);
if (enumType == typeof(Enum))
throw new ArgumentException("typeof(TEnum) == System.Enum", "TEnum");
if (!(enumType.IsEnum))
throw new ArgumentException(String.Format("typeof({0}).IsEnum == false", enumType), "TEnum");
return Enum.GetValues(enumType).OfType<TEnum>();
}
Krzysztof - good catch. I should have been more specific and noted that this approach has only been tested with mutually exclusive elements.
Thanks,
Alnur
Hello,
Great stuff, but will not work for Silverlight
To obtain the same in silverlight, refer to the link below
aspdotnethacker.blogspot.com/.../hello-folks-while-working-on-my-project.html