Iterating over enumeration values in C#
Declaring an enumeration in C# allows you to define a set of named constants. Iterating over these values can be useful in a variety of situations.
To iterate over enumeration values, you can utilize the Enum.GetValues
method. Consider the following Foos
enumeration:
public enum Foos { A, B, C }
Using Enum.GetValues
you can retrieve an array of enumeration values like this:
var values = Enum.GetValues(typeof(Foos));
Alternatively, for the typed version, you can use:
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
To simplify this process, you can implement a helper function, for example:
public static class EnumUtil { public static IEnumerable<T> GetValues<T>() { return Enum.GetValues(typeof(T)).Cast<T>(); } }
Using this helper function, you can iterate over enumeration values using:
var values = EnumUtil.GetValues<Foos>();
The above is the detailed content of How Can I Iterate Through Enum Values in C#?. For more information, please follow other related articles on the PHP Chinese website!