Home >Backend Development >C++ >How to Iterate Through Enum Values in C#?

How to Iterate Through Enum Values in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-17 09:26:16754browse

How to Iterate Through Enum Values in C#?

Traverse C# enumeration values

In C#, enumerations are a convenient way to represent a fixed set of values. When working with an enumeration, you often need to iterate over its possible values. This can be achieved using the Enum method provided by the GetValues class.

Consider the following enumeration:

<code class="language-csharp">public enum Foos
{
    A,
    B,
    C
}</code>

To iterate over the values ​​of this enumeration, you can use the following code:

<code class="language-csharp">var values = Enum.GetValues(typeof(Foos));
foreach (var foo in values)
{
    // 对当前值执行操作
}</code>

Alternatively, you can use the typed version of GetValues to retrieve the value directly as an enum type:

<code class="language-csharp">var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
foreach (var foo in values)
{
    // 对当前值执行操作
}</code>

For convenience, you can also create a helper function to simplify this process:

<code class="language-csharp">public static class EnumUtil
{
    public static IEnumerable<T> GetValues<T>()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }
}</code>

To use this helper function, just call:

<code class="language-csharp">var values = EnumUtil.GetValues<Foos>();
foreach (var foo in values)
{
    // 对当前值执行操作
}</code>

The above is the detailed content of How to Iterate Through Enum Values in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn