tags:

views:

78

answers:

4

Hi, I want to have an enum like the following and then have a method something like Util.FindFruitByValue("A") which returns the enum Apple. this is because the abbreviations are stored in database and I need to convert them to appropriate enums after reading from db. is this possible OR do I need to create a separate class for it? Please let me know. thanks in advance.

public enum Fruit
{
    Apple = "A"
    Banana = "B"
    Cherry = "C"
}

Update: this is like a lookup table, but the difference is the value is string instead of an int. I am populating a business object, by reading the values from database and I would like to use a type with fixed values for the object property instead of string.

+1  A: 

How about using Hashtable?

rursw1
+1  A: 

Sorry, I overlooked the definition of the OP's Enum. Obviously, the Enum values have to be a numeric type, so the OP's definition won't work.

One thought I had was to use the char value as the Enum value, e.g.

public enum Fruit
{
    Apple  = 65, //"A",
    Banana = 66, // "B",
    Cherry = 67 //"C"
}

As per Convert.ToInt32('A') - not sure what to do with case sensitivity here. Then, grab the correct result by casting. I'm still playing around with an example, happy to hear some suggestions.

OK, sorry for the delay. Here's a bit more on this:

public static class EnumConverter<T>
{
    public static T ToEnum(char charToConvert, out bool success)
    {
        try
        {                
            int intValue = Convert.ToInt32(charToConvert);                
            if (Enum.IsDefined(typeof(T), intValue))
            {
                success = true;
                return (T)Enum.ToObject(typeof(T), intValue);
            }
       }
       catch (ArgumentException ex)
       {
               // Use your own Exception Management Here
       }
       catch (InvalidCastException ex)
       {
           // Use your own Exception Management Here
       }
       success = false;
       return default(T);
    }
}

Usage:

bool success = false;
Fruit selected = EnumConverter<Fruit>.ToEnum('A', out success);
if (success)
{
   // go for broke
}
RobS
He wants to put in `"A"` and get out `Fruit.Apple`, is that what your code does?
Benjol
@Benjol : Yes, that's what it does. It will also return Fruit.Apple for the string "Apple".
Lazarus
Can you show how the `Fruit` enum should be defined to make this work?
Ben Voigt
Obviously you can't have an Enum with string values, what you could do is convert 'A', 'B' to Int and then do a cast. E.g. Apple = 65
RobS
+2  A: 

You can put the values in a Dictionary to efficiently look them up:

Dictionary<string, Fruit> fruitValues = new Dictionary<string, Fruit>();
fruitValues.Add("A", Fruit.Apple);
fruitValues.Add("B", Fruit.Banana);
fruitValues.Add("C", Fruit.Cherry);

Lookup:

string dataName = "A";
Fruit f = fruitValues[dataName];

If the value may be non-existent:

string dataName = "A";
Fruit f;
if (fruitValues.TryGetValue(dataName, out f)) {
  // got the value
} else {
  // there is no value for that string
}
Guffa
A: 

I solved the problem by using the Description attribute on the enum. the solution is as follows. I use the extension method to get the description. the code to get the description is taken from this link http://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx. thanks for your replies.

    public enum Fruit
{
    [Description("Apple")]
    A,
    [Description("Banana")]
    B,
    [Description("Cherry")]
    C
}

public static class Util
{
    public static T StringToEnum<T>(string name)
    {
        return (T)Enum.Parse(typeof(T), name);
    }

    public static string ToDescriptionString(this Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }
}
RKP
Nothin' like a bit of Reflection...
RobS
actually reflection is slow in general, but I couldn't figure out any other way to solve this problem. I need a type with fixed values and instead of creating a custom class for different types of such information, enum is convenient to use, but lacks support for string values which is why I had to choose this option. I would welcome any suggestions to accomplish this in a better way.
RKP