Home >Backend Development >C++ >How Can I Efficiently Iterate Through C# Enumerations?

How Can I Efficiently Iterate Through C# Enumerations?

Linda Hamilton
Linda HamiltonOriginal
2025-01-17 09:32:13334browse

How Can I Efficiently Iterate Through C# Enumerations?

Detailed explanation of C# enumeration traversal method

C# enumerations provide a structured way to represent a fixed set of values. However, sometimes you need to iterate over the values ​​in an enumeration efficiently.

C# provides the Enum.GetValues method for this purpose. This method accepts an enumeration type as argument and returns an array containing the underlying value. By converting this array to the corresponding enum type, you can conveniently iterate over the enum values ​​using a foreach loop.

For example, 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 Enum.GetValues method as follows:

<code class="language-csharp">var values = Enum.GetValues(typeof(Foos));

foreach (var value in values)
{
    Console.WriteLine(value);
}</code>

This code outputs the values ​​"A", "B" and "C" to the console.

Additionally, C# provides a convenient way to iterate over enumeration values ​​while ensuring type safety. The following code snippet demonstrates how to achieve this using the typed version of the Enum.GetValues method:

<code class="language-csharp">var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();

foreach (var value in values)
{
    // 现在你拥有一个 Foos 类型的强类型值
}</code>

To further simplify enumeration iteration, a helper function can be defined in the code base. For example:

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

This helper function can then be used to iterate over the enumeration values ​​like this:

<code class="language-csharp">var values = EnumUtil.GetValues<Foos>();

foreach (var value in values)
{
    // 在这里,你可以访问 Foos 枚举的值
}</code>

The above is the detailed content of How Can I Efficiently Iterate Through C# Enumerations?. 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