Wednesday, 11 October 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...