How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
I think this is more efficient than other suggestions because GetValues()
is not called each time you have a loop. It is also more concise. And you get a compile-time error, not a runtime exception if Suit
is not an enum
.
EnumLoop<Suit>.ForEach((suit) => {
DoSomethingWith(suit);
});
EnumLoop
has this completely generic definition:
class EnumLoop<Key> where Key : struct, IConvertible {
static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
static internal void ForEach(Action<Key> act) {
for (int i = 0; i < arr.Length; i++) {
act(arr[i]);
}
}
}
I use ToString() then split and parse the spit array in flags.
[Flags]
public enum ABC {
a = 1,
b = 2,
c = 4
};
public IEnumerable<ABC> Getselected (ABC flags)
{
var values = flags.ToString().Split(',');
var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));
return enums;
}
ABC temp= ABC.a | ABC.b;
var list = getSelected (temp);
foreach (var item in list)
{
Console.WriteLine(item.ToString() + " ID=" + (int)item);
}
What if you know the type will be an enum
, but you don't know what the exact type is at compile time?
public class EnumHelper
{
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
public static IEnumerable getListOfEnum(Type type)
{
MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod("GetValues").MakeGenericMethod(type);
return (IEnumerable)getValuesMethod.Invoke(null, null);
}
}
The method getListOfEnum
uses reflection to take any enum type and returns an IEnumerable
of all enum values.
Usage:
Type myType = someEnumValue.GetType();
IEnumerable resultEnumerable = getListOfEnum(myType);
foreach (var item in resultEnumerable)
{
Console.WriteLine(String.Format("Item: {0} Value: {1}",item.ToString(),(int)item));
}
Also you can bind to the public static members of the enum directly by using reflection:
typeof(Suit).GetMembers(BindingFlags.Public | BindingFlags.Static)
.ToList().ForEach(x => DoSomething(x.Name));
I think you can use
Enum.GetNames(Suit)
Just by combining the top answers, I threw together a very simple extension:
public static class EnumExtensions
{
/// <summary>
/// Gets all items for an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>(this T value) where T : Enum
{
return (T[])Enum.GetValues(typeof (T));
}
}
It is clean, simple, and, by @Jeppe-Stig-Nielsen's comment, fast.