Dictionary of enum values ​​as strings

I am trying to create an API, one function in this API takes an Enum parameter as a parameter, which then matches the string used.

public enum PackageUnitOfMeasurement
{
        LBS,
        KGS,
};

      

A trivial method for this code would be to list every case in the code. But since there are 30 cases of them, so I try to avoid that and use it Dictionary Data Structure

, but I can't seem to connect the dots to how to bind the value to the enum.

if(unit == PackageUnitOfMeasurement.LBS)
       uom.Code = "02";  //Please note this value has to be string
else if (unit == PackageUnitOfMeasurement.KGS)
       uom.Code = "03";

      

+3


source to share


5 answers


Here's one way to store the match in a dictionary and retrieve the values ​​later:

var myDict = new Dictionary<PackageUnitOfMeasurement,string>();
myDict.Add(PackageUnitOfMeasurement.LBS, "02");
...

string code = myDict[PackageUnitOfMeasurement.LBS];

      

Another option is to use something like DecriptionAttribute

to decorate each element of the enum and use reflection to read them, as described in Retrieving Enum Value Attributes :



public enum PackageUnitOfMeasurement
{
        [Description("02")]
        LBS,
        [Description("03")]
        KGS,
};


var type = typeof(PackageUnitOfMeasurement);
var memInfo = type.GetMember(PackageUnitOfMeasurement.LBS.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
    false);
var description = ((DescriptionAttribute)attributes[0]).Description;

      

The advantage of the second approach is that you keep the display close to the enumeration, and if there are any changes, you do not need to look for some other place that you need to update.

+9


source


You can specify the numeric value of the enum members

public enum PackageUnitOfMeasurement {
    None = 0,
    LBS = 2,
    KGS = 3,
    TONS = 0x2a
};

      

Then you can simply convert the units with

uom.Code = ((int)unit).ToString("X2");

      




Note:

The main question is whether it is a good idea to hard-code the units. Usually such things should be entered into the lookup table in the database, which makes it easy to add new devices at any time without changing the program code.




UPDATE:

I have added an example containing HEX code. The X2 format gives a two-digit hexadecimal value. Enter numbers greater than 9 in hexadecimal notation, such as 0xA == 10

, 0x10 == 16

in C #.

+4


source


I would use enumeration related attributes. Like this:

var type = typeof(PackageUnitOfMeasurement);
var memInfo = type.GetMember(PackageUnitOfMeasurement.LBS.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
    false);
var description = ((DescriptionAttribute)attributes[0]).Description;

      

This is taken from this question, Retrieving Enum Value Attributes . Which specifically talks about returning Enum attributes.

+2


source


The oded solution is fine, but the alternative I've used in the past is to use attributes associated with the enum values ​​that contain the corresponding string.

Here's what I did.

public class DisplayStringAttribute : Attribute
{
    private readonly string value;
    public string Value
    {
        get { return value; }
    }

    public DisplayStringAttribute(string val)
    {
        value = val;
    }
}

      

Then I could define my enum like this:

public enum MyState 
{ 
    [DisplayString("Ready")]
    Ready, 
    [DisplayString("Not Ready")]
    NotReady, 
    [DisplayString("Error")]
    Error 
};

      

And for my purposes, I created a converter so that I can bind to an enum:

public class EnumDisplayNameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Type t = value.GetType();
        if (t.IsEnum)
        {
            FieldInfo fi = t.GetField(value.ToString());
            DisplayStringAttribute[] attrbs = (DisplayStringAttribute[])fi.GetCustomAttributes(typeof(DisplayStringAttribute),
                false);
            return ((attrbs.Length > 0) && (!String.IsNullOrEmpty(attrbs[0].Value))) ? attrbs[0].Value : value.ToString();
        }
        else
        {
            throw new NotImplementedException("Converter is for enum types only");
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

      

Oded's solution is probably faster, but this solution has a lot of flexibility. You could add a whole bunch of attributes if you like. However, if you've done that, you're probably better off creating a class rather than using an enum!

+1


source


The default PackageUnitOfMeasurement.LBS

is 0 and PackageUnitOfMeasurement.KBS

is 1 .

So a collection PackageUnitOfMeasurement

is really a collection containing integer values ​​(i.e. int

).

Your question is not entirely clear ....

A collection of dictionaries has, Key

and Value

it looks like you want to use PackageUnitOfMeasurement has Key

, which is trivial as a distinct integer value.

PackageUnitOfMeasurement example = PackageUnitOfMeasurement.LBS
int result = (int)example;
var myDict = new Dictionary<PackageUnitOfMeasurement,string>(); 
myDict.Add(result,"some value here"

      

0


source







All Articles