C#C
C#3y ago
14 replies
SWEETPONY

✅ How to get values of list using reflection?

Recently I wrote some logic to get values from enum:
private JArray GetOptions( Type type, CultureInfo culture )
{
    var fields = type.IsEnum
       ? type.GetFields(BindingFlags.Public | BindingFlags.Static)
       : type.GetGenericArguments()[0]
            .GetFields(BindingFlags.Public | BindingFlags.Static);

    return new JArray(fields.Select(field =>
    {
        var value = field.GetCustomAttribute<EnumMemberAttribute>()
                ?.Value ?? field.Name;

        var label =
           field.GetCustomAttribute<TitleLocalizedAttribute>()
               ?.ValueGet(field.Name, culture)
           ?? field.GetCustomAttribute<TitleAttribute>()?.Title
           ?? field.Name;

        return new JObject
        {
           ["label"] = label,
           ["value"] = value
        };
    } ) );
}


everything works good, I can work with IEnumerable<T> or just
T
where
T
is Enum
but now I need to get values from IEnumerable<string> or string:
List<string> str {get;set;} = new() {"a","b"};

so I wanna fill Jarray with a and b. How can I do it?
I apologize for the question posted. I'm just tired and not thinking straight
Was this page helpful?