Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum in C# and foreach [duplicate]

Tags:

c#

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}
};
like image 935
Amira Elsayed Ismail Avatar asked Oct 13 '10 10:10

Amira Elsayed Ismail


People also ask

What is an enum in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

What is enum example?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

What are enums used for?

An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties.

Where is enum used in C?

Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.


1 Answers

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();
like image 155
Jon Skeet Avatar answered Oct 13 '22 16:10

Jon Skeet