简体   繁体   中英

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"

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 .

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM