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

How to Iterate Through Enum Values in C#?

Linda Hamilton
Release: 2025-01-17 09:26:16
Original
753 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

To use this helper function, just call:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template