0

below is the Enum from which i need to populate object list

public enum Scope
    {
        [Description("Organization")]
        Organization = 100,
        [Description("Organization@Unit")]
        Organization_Unit = 200,
        [Description("Organization@Unit@User")]
        Organization_Unit_User = 300
    }

I have to create object list from this Enum

Object skeleton will be like below

public class ScopeKVP {
  public string key {get;set;}
  public int value {get;set;}
}

At the end I need below list of object from enum in which description of each enum should be save in key property of object and value of enum should be saved in value property of object like below

var scopeKvp = new List<ScopeKVP> {
    new ScopeKVP {key= 100,value="Organization"},
    new ScopeKVP {key= 200,value="Organization@Unit"},
    new ScopeKVP {key= 300,value="Organization@Unit@User"}
}
Rajiv
  • 1,245
  • 14
  • 28
  • 1
    [This](https://stackoverflow.com/questions/1799370/getting-attributes-of-enums-value) quesiton shows how to get the attributes from the enum values. Constructing the list should then be easy. (Note that `key = 100` is wrong when `key` is of type `string`). – René Vogt May 08 '20 at 09:19
  • Here's an article on this on how to get attributes and their values from instances: https://www.codementor.io/@cerkit/giving-an-enum-a-string-value-using-the-description-attribute-6b4fwdle0 – KingOfArrows May 08 '20 at 09:20
  • And I'd recommend to use a `Dictionary` instead of the list. – René Vogt May 08 '20 at 09:24
  • 2
    TBH, This is looks like a misuse of the enum language feature – TheGeneral May 08 '20 at 09:34

1 Answers1

0

This is what you need to do:

  1. Use reflection to get the information about the enum, its fields
  2. Loop the fields
  3. Take their value with GetValue method
  4. Take the attribute Description's description, which is what you passed to its constructor
  5. Create the object of type ScopeKVP and add it to the result list

Code:

    Type enumType = typeof(Scope);
    FieldInfo[] fields = enumType.GetFields();

    List<ScopeKVP> scopeKvp = new List<ScopeKVP>();
    foreach (FieldInfo field in fields)
    {
        if (field.IsLiteral)
        {
            DescriptionAttribute descAttr = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));

            ScopeKVP item = new ScopeKVP()
            {
                key = descAttr.Description,
                value = (int)field.GetValue(null)
            };

            scopeKvp.Add(item);
        }
    }

    // scopeKvp is what you need

P.S. like the comments above state, you have some mismatch for key which is string and you expect integer. I guess it is a typo.

antanta
  • 618
  • 8
  • 16