20

Possible Duplicate:
C#: How to enumerate an enum?

Hi All,

I have an Enum

public enum AttributeType
    {
        TextField = 1, 
        TextArea = 2,
        Date = 4, 
        Boolean = 8
    }

I want to foreach this enum and make an object array of it in this format

object data = new object[]
{
   // new object[] { 1,"TextField"}
   new object[] { enumValue, enumText}
};
1

1 Answer 1

30

Well, this would do it (assuming .NET 3.5):

var allValues = (AttributeType[]) Enum.GetValues(typeof(AttributeType));

var array = allValues.Select(value => new object[] { value, value.ToString() })
                     .ToArray();

or use an anonymous type:

var array = allValues.Select(value => { Value = value, Name = value.ToString() })
                     .ToArray();
Sign up to request clarification or add additional context in comments.

3 Comments

You dont really need that (AttributeType[]) :)
@leppie: You either need that or a call to Cast, given that Enum.GetValues just returns Array.
Argh, you are right as usual, I was thinking (incorrectly) it would be IEnumerable<object> anyways... (oops).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.