Search code examples
c#.netpocketpc

How to Enum.GetValues in .Net 3.5?


In .Net 4.0, I use System.Enum.GetValues(typeof(Gender)) to get the list of enum item.
In a complete example, I use to look for enum value in this way:

    Gender retVal = Gender.Male;

    foreach (Gender enumType in System.Enum.GetValues(typeof(Gender)))
    {
        if (enumType.ToString().Trim().ToUpper().Substring(0,1).Equals(stringToEnum.Trim().ToUpper()))
        {
            retVal = enumType;
            break;
        }
    }  

But how could I do this in .Net 3.5 (Pocket PC) ?
Thanks in advance !

I use the answers below but It doesn't work for me. Here's the code:

Enum Values:

namespace Ionic.Zlib
{
    public enum CompressionLevel
    {
        Level0 = 0,
        None = 0,
        Level1 = 1,
        BestSpeed = 1,
        Level2 = 2,
        Level3 = 3,
        Level4 = 4,
        Level5 = 5,
        Level6 = 6,
        Default = 6,
        Level7 = 7,
        Level8 = 8,
        BestCompression = 9,
        Level9 = 9,
    }
}  

Usage:

I just miss to initialize new object. This works now:

public static Ionic.Zlib.CompressionLevel GetCompressionLevel(string Expression)
{
    Ionic.Zlib.CompressionLevel result = Ionic.Zlib.CompressionLevel.None;
    foreach (Ionic.Zlib.CompressionLevel item in EnumGetValues(new Ionic.Zlib.CompressionLevel()))
    {
        if(object.Equals(item.ToString().Trim().ToUpper(), Expression.Trim().ToUpper()))
        {
            result = item;
            break;
        }
    }
    return result;
}

Solution

  • There's a blog post here (archived here) which achieves it via reflection:

    public IEnumerable<Enum> GetValues(Enum enumeration)
    {
        List<Enum> enumerations = new List<Enum>();
        foreach (FieldInfo fieldInfo in enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
        {
            enumerations.Add((Enum)fieldInfo.GetValue(enumeration));
        }
        return enumerations;
    }