-4
public enum States
{
        [Description("New Hampshire")]
        NewHampshire = 29,
        [Description("New York")]
        NewYork = 32,
}

Here I have to get the data by Description example: I need 29 by 'New Hampshire' Dynamically not using index position

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

3 Answers3

0

this is a way you can:

States s;
var type = typeof(States);
foreach (var field in type.GetFields())
{
    var attribute = Attribute.GetCustomAttribute(field,
        typeof(DescriptionAttribute)) as DescriptionAttribute;
    if (attribute != null)
    {
        if (attribute.Description == "description")
        {
            s = (States)field.GetValue(null);
            break;
        }
    }
    else
    {
        if (field.Name == "description")
        {
            s = (Rule)field.GetValue(null);
            break;
        }
    }
} 
filhit
  • 2,084
  • 1
  • 21
  • 34
israel altar
  • 1,768
  • 1
  • 16
  • 24
0

You can pass your string to GetDataByDescription method. I've used answer by Aydin Adn for GetAttribute method.

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(GetDataByDescription("New Hampshire"));
    }

    private static int GetDataByDescription(string s)
    {
        foreach (States state in Enum.GetValues(typeof (States)))
        {
            if (GetAttribute<DescriptionAttribute>(state).Description == s)
            {
                return (int) state;
            }
        }

        throw new ArgumentException("no such state");
    }

    private static TAttribute GetAttribute<TAttribute>(Enum enumValue)
        where TAttribute : Attribute
    {
        return enumValue.GetType()
            .GetMember(enumValue.ToString())
            .First()
            .GetCustomAttribute<TAttribute>();
    }
}
filhit
  • 2,084
  • 1
  • 21
  • 34
-1

Here a generic method you can use with any attribute

public static class Extensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) 
            where TAttribute : Attribute
    {
        return enumValue.GetType()
                        .GetMember(enumValue.ToString())
                        .First()
                        .GetCustomAttribute<TAttribute>();
    }
}

This will help you achieve what you're attempting...

Aydin
  • 15,016
  • 4
  • 32
  • 42