Wednesday, 10 May 2017

Enum in C# and foreach










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}
};

Answer



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();

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...