Say that we have the following Enum:
public enum EnumStatus { [Description("Not Submitted")] NotSubmitted = 0, Requested = 1, [Description("Pending Approval")] PendingApproval = 2, Approved = 3, Rejected = 4 }
Then the code to get each element's value and Description attribute (or name) is:
var type = typeof(EnumStatus); foreach (var field in type.GetFields().Where(f => f.FieldType == type)) { var attribute = Attribute.GetCustomAttribute(field, typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute; var value = field.GetValue(Activator.CreateInstance(type)); myCollections.Add( new { Id = (int)value, Name = attribute != null ? attribute.Description : value.ToString() // or Enum.GetName(typeof(EnumStatus), value) } ); }
No comments:
Post a Comment