Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert from enum to IEnumerable

Tags:

c#

enums

Can you help me hww to corect this code

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace NTSoftHRM
{

    // ------------------------------------------------------------------------
    public class EnumValueList<T> : IEnumerable<T>
    {

        // ----------------------------------------------------------------------
        public EnumValueList()
        {
            IEnumerable<T> enumValues = GetEnumValues();
            foreach ( T enumValue in enumValues )
            {
                enumItems.Add( enumValue );
            }
        } // EnumValueList

        // ----------------------------------------------------------------------
        protected Type EnumType
        {
            get { return typeof( T ); }
        } // EnumType

        // ----------------------------------------------------------------------
        public IEnumerator<T> GetEnumerator()
        {
            return enumItems.GetEnumerator();
           // return ((IEnumerable<T>)enumItems).GetEnumerator();

        } // GetEnumerator

        // ----------------------------------------------------------------------
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        } // GetEnumerator

        // ----------------------------------------------------------------------
        // no Enum.GetValues() in Silverlight
        private IEnumerable<T> GetEnumValues()
        {
            List<T> enumValue = new List<T>();

            Type enumType = EnumType;

            return Enum.GetValues(enumType);

        } // GetEnumValues

        // ----------------------------------------------------------------------
        // members
        private readonly List<T> enumItems = new List<T>();

    } // class EnumValueList

} 

when bulid the error is: Cannot implicitly convert type 'System.Array' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) at return Enum.GetValues(enumType)

like image 667
chung pham nhu Avatar asked Nov 11 '13 15:11

chung pham nhu


2 Answers

The issue is in your GetEnumValues method, Enum.GetValues returns an Array not an IEnumerable<T>. You need to cast it i.e.

Enum.GetValues(typeof(EnumType)).Cast<EnumType>();
like image 196
James Avatar answered Oct 03 '22 07:10

James


    private IEnumerable<T> GetEnumValues()
    {
        Type enumType = EnumType;

        return Enum.GetValues(enumType).ToList<T>();
    } 
like image 43
Jakub Konecki Avatar answered Oct 03 '22 07:10

Jakub Konecki