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:
<code class="language-csharp">public enum Foos { A, B, C }</code>
Using Enum.GetValues
you can retrieve an array of enumeration values like this:
<code class="language-csharp">var values = Enum.GetValues(typeof(Foos));</code>
Alternatively, for the typed version, you can use:
<code class="language-csharp">var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();</code>
To simplify this process, you can implement a helper function, for example:
<code class="language-csharp">public static class EnumUtil { public static IEnumerable<T> GetValues<T>() { return Enum.GetValues(typeof(T)).Cast<T>(); } }</code>
Using this helper function, you can iterate over enumeration values using:
<code class="language-csharp">var values = EnumUtil.GetValues<Foos>();</code>
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!