prospector
prospector

Reputation: 3469

Get the name of a property by the value

I'd rather be using Enums but I need an easy way to display strings.

 public struct OpportunityStatus
    {
        public static string Active { get; } = "stat_WWuMrC5QlVlr7geYuxDStp5BfrEtfl63H8JaQoIdYAG";
        public static string Lost { get; } = "stat_LOjFr8l9IG0XQ0Wq23d0uiXe3fDEapCW7vsGECZnKy4";
    }

This works fine if I need to get the status code of a lost opportunity in my code without typing the status code. It helps with the readability, same as an emum.

How do I do it in reverse though? How can I get the property name by the string value:

    public static object FindByStatusCode(string statusCode)
    {
        return typeof(LeadStatus)
           .GetProperty("stat_WWuMrC5QlVlr7geYuxDStp5BfrEtfl63H8JaQoIdYAG");
    }

Should return "Active"

Upvotes: 0

Views: 418

Answers (3)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You seem to have some mapping from a string-value to a property. Thus you should also use a data-structure that supports mapping keys to values. Best option thus is a Dictionary:

var map = new Dictionary<string, string> { 
    { "Active", "stat_WWuMrC5QlVlr7geYuxDStp5BfrEtfl63H8JaQoIdYAG" }, 
    { "Lost", "stat_LOjFr8l9IG0XQ0Wq23d0uiXe3fDEapCW7vsGECZnKy4" }
};

Now you can get the key that maps to a given value:

var name = map.FirstOrDefault(x => x.Value == "stat_WWuMrC5QlVlr7geYuxDStp5BfrEtfl63H8JaQoIdYAG");

Depending on if you need to get keys by values more often you may also exchange key and value, making "Active" the actual value in the dictionary, instead of the key.

Upvotes: 0

torsan
torsan

Reputation: 489

It looks like you are trying to implement a 'smart' enum. Check out ardalis on git hub. enter link description here

You can also find this code as a NuGet package.

Upvotes: 0

Ron Beyer
Ron Beyer

Reputation: 11273

Yes, this is possible using reflection, but be aware that it can be very slow...

    public static string GetPropertyByValue(Type staticClass, string value)
    {
        var typeInfo = staticClass.GetProperties(BindingFlags.Static | BindingFlags.Public)
                                                .Where(p => string.Compare(p.GetValue(null) as string, value) == 0)
                                                .FirstOrDefault();
        return typeInfo?.Name;
    }

This will return the name of a static property with a certain value. It requires that the property be static.

You can call it like this:

var name = GetPropertyByValue(typeof(OpportunityStatus), "stat_WWuMrC5QlVlr7geYuxDStp5BfrEtfl63H8JaQoIdYAG");

Where name will equal Active.

Upvotes: 3

Related Questions