Need a good way to store Name value pairs

I often come across a situation where I want to have a set of key / value pairs. Here's the idea of ​​pseudocode:

DataSet MyRequestStatus
{
  Accepted = "ACC",
  Rejected = "REJ"
}

Using:

InsertIntoTable(MyRequestStatus.Accepted.ToString())

I want to use the friendly "MyRequestStatus.Accepted", but I want ToString () to return a critical "ACC" rather than "Accepted". Bonus points, implicit conversion, not a call to ToString ().

I did not find an obvious way to achieve this with Enums. What are you offering?

+3
source share
4 answers
public static class MyRequestStatus
{
    public const string Accepted = "ACC",
                        Rejected = "REJ";
}
+5
source

try it

public struct MyRequestStatus
{
    public static string Accepted = @"ACC";
    public static string Rejected = @"REJ";
}
0
source
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, string> d = new Dictionary<string, string>();
        d.Add("Accepted", "ACC");
        d.Add("Rejected", "REJ");

        string r = d["Rejected"];
    }
}

API .

0

Either use a class with constant lines, as suggested by Mark Gravell , or if you want to keep the enumeration, set up a static dictionary to contain the mappings:

private static Dictionary<MyRequestStatus, string> requestStatusToString = 
   new Dictionary<MyRequestStatus, string>()
{
   { MyRequestStatus.Accepted, "ACC" },
   { MyRequestStatus.Rejected, "REJ" }
};

Then you can do:

MyRequestStatus status = MyRequestStatus.Accepted;
string code = requestStatusToString[status];
0
source

Source: https://habr.com/ru/post/1774314/


All Articles