How to enumerate an enum

后端 未结 29 1843
深忆病人
深忆病人 2020-11-22 01:14

How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{         


        
相关标签:
29条回答
  • 2020-11-22 01:35

    If you have:

    enum Suit
    {
       Spades,
       Hearts,
       Clubs,
       Diamonds
    }
    

    This:

    foreach (var e in Enum.GetValues(typeof(Suit)))
    {
        Console.WriteLine(e.ToString() + " = " + (int)e);
    }
    

    Will output:

    Spades = 0
    Hearts = 1
    Clubs = 2
    Diamonds = 3
    
    0 讨论(0)
  • 2020-11-22 01:35

    LINQ Generic Way:

        public static Dictionary<int, string> ToList<T>() where T : struct =>
            ((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(value => Convert.ToInt32(value), value => value.ToString());
    

    Usage:

            var enums = ToList<Enum>();
    
    0 讨论(0)
  • 2020-11-22 01:36

    I made some extensions for easy enum usage. Maybe someone can use it...

    public static class EnumExtensions
    {
        /// <summary>
        /// Gets all items for an enum value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static IEnumerable<T> GetAllItems<T>(this Enum value)
        {
            foreach (object item in Enum.GetValues(typeof(T)))
            {
                yield return (T)item;
            }
        }
    
        /// <summary>
        /// Gets all items for an enum type.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static IEnumerable<T> GetAllItems<T>() where T : struct
        {
            foreach (object item in Enum.GetValues(typeof(T)))
            {
                yield return (T)item;
            }
        }
    
        /// <summary>
        /// Gets all combined items from an enum value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        /// <example>
        /// Displays ValueA and ValueB.
        /// <code>
        /// EnumExample dummy = EnumExample.Combi;
        /// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())
        /// {
        ///    Console.WriteLine(item);
        /// }
        /// </code>
        /// </example>
        public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
        {
            int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
    
            foreach (object item in Enum.GetValues(typeof(T)))
            {
                int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);
    
                if (itemAsInt == (valueAsInt & itemAsInt))
                {
                    yield return (T)item;
                }
            }
        }
    
        /// <summary>
        /// Determines whether the enum value contains a specific value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="request">The request.</param>
        /// <returns>
        ///     <c>true</c> if value contains the specified value; otherwise, <c>false</c>.
        /// </returns>
        /// <example>
        /// <code>
        /// EnumExample dummy = EnumExample.Combi;
        /// if (dummy.Contains<EnumExample>(EnumExample.ValueA))
        /// {
        ///     Console.WriteLine("dummy contains EnumExample.ValueA");
        /// }
        /// </code>
        /// </example>
        public static bool Contains<T>(this Enum value, T request)
        {
            int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
            int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);
    
            if (requestAsInt == (valueAsInt & requestAsInt))
            {
                return true;
            }
    
            return false;
        }
    }
    

    The enum itself must be decorated with the FlagsAttribute:

    [Flags]
    public enum EnumExample
    {
        ValueA = 1,
        ValueB = 2,
        ValueC = 4,
        ValueD = 8,
        Combi = ValueA | ValueB
    }
    
    0 讨论(0)
  • 2020-11-22 01:36

    I tried many ways and got the result from this code:

    For getting a list of int from an enum, use the following. It works!

    List<int> listEnumValues = new List<int>();
    YourEnumType[] myEnumMembers = (YourEnumType[])Enum.GetValues(typeof(YourEnumType));
    foreach ( YourEnumType enumMember in myEnumMembers)
    {
        listEnumValues.Add(enumMember.GetHashCode());
    }
    
    0 讨论(0)
  • 2020-11-22 01:37

    Use Cast<T>:

    var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();
    

    There you go, IEnumerable<Suit>.

    0 讨论(0)
  • 2020-11-22 01:37

    My solution works in .NET Compact Framework (3.5) and supports type checking at compile time:

    public static List<T> GetEnumValues<T>() where T : new() {
        T valueType = new T();
        return typeof(T).GetFields()
            .Select(fieldInfo => (T)fieldInfo.GetValue(valueType))
            .Distinct()
            .ToList();
    }
    
    public static List<String> GetEnumNames<T>() {
        return typeof (T).GetFields()
            .Select(info => info.Name)
            .Distinct()
            .ToList();
    }
    
    • If anyone knows how to get rid of the T valueType = new T(), I'd be happy to see a solution.

    A call would look like this:

    List<MyEnum> result = Utils.GetEnumValues<MyEnum>();
    
    0 讨论(0)
提交回复
热议问题