-1

In an attempt to build a Dictionary object that is seeded with all possible system statuses as the keys and 0 for each value, I have the following code that loops through the Enum that contains system status info:

            Dictionary<string, int> statusAccumulator = new Dictionary<string, int>();

            // initialize statusAccumulator with all possible system statuses
            foreach (var status in Enum.GetNames(typeof(SystemTaskRequestStatus)))
            {
                statusAccumulator[status] = 0;
            }

and here is the Enum for system status:

public enum SystemStatus
{
    [EnumString("PN")]
    Pending,
    [EnumString("RT")]
    Retry,
    [EnumString("IP")]
    InProgress,
    [EnumString("C")]
    Complete,
    [EnumString("F")]
    Failed,
    [EnumString("T")]
    Test
}

With this code, the keys in the Dictionary are: Pending, Retry, InProgress, Complete, Failed, Test. However, I want the EnumStrings as the keys - PN, RT, IP, C, F, T. How can the code be modified to achieve this?

knot22
  • 2,648
  • 5
  • 31
  • 51
  • 1
    Possible duplicate of [Getting attributes of Enum's value](https://stackoverflow.com/questions/1799370/getting-attributes-of-enums-value) – Babak Naffas Jan 22 '19 at 18:08
  • 2
    Why would you want to? Is `statusAccumulator[SystenStatus.Pending]` too long? The point of an enum is to reduce ambiguity, not create it. – Enfyve Jan 22 '19 at 18:09

2 Answers2

0

Can't you do Enum.GetValues(typeof(SystemStatus)), apply foreach, cast each item back to enum then use whatever method that retrieves the string from the property?

foreach (var status in Enum.GetValues(typeof(SystemStatus))
{
    string key = (SystemStatus)status.MethodThatRetrievesTheThingyFromProperty();
    statusAccumulator[key] = 0;
}

However, is there a reason why you don't want to use SystemStatus as TKey and use the enum instance itself to get/set the value?

Dictionary<SystemStatus, int> statusAccumulator = new Dictionary<SystemStatus, int>();

// initialize statusAccumulator with all possible system statuses
foreach (var status in Enum.GetValues(typeof(SystemStatus))
{
    statusAccumulator[(SystemStatus)status] = 0;
}
Gnbrkm41
  • 238
  • 3
  • 9
0

Try replace you enum code with this, public enum SystemStatus { [StringValue("PN")] PN = 1, [StringValue("RT")] RT = 2, [StringValue("IP")] IP = 3, [StringValue("C")] C = 4, [StringValue("F")] F = 5 [StringValue("T")] T = 6 }

Anu Singh
  • 19
  • 3