anhtv13
anhtv13

Reputation: 1818

C# How can I get a list of enum string in [EnumMember]?

I try to get the list of values in [EnumMember] but it doesn't work. It returns a list of enum names, not values in [EnumMember].

I take an example to demonstrate what I want:

CarEnum.cs

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum CarEnum
{
    [EnumMember(Value = @"Rolls Royce")]
    RollsRoyce=1,

    [EnumMember(Value = @"Honda")]
    Honda = 2,

    [EnumMember(Value = @"Mercedes Benz")]
    MercedesBenz = 3,
}

This is the code I try to get the values:

var carList = Enum.GetValues(typeof(CarEnum)).Cast<CarEnum>()
                            .Select(x => x.ToString())
                            .ToList();

The carList returns a list of ["RollsRoyce", "Honda", "MercedesBenz"].

I expect it to return ["Rolls Royce", "Honda", "Mercedes Benz"] (the values contain space in the brand names).

Please let me know if you can help me out.

Thanks.

Upvotes: 1

Views: 1862

Answers (1)

anhtv13
anhtv13

Reputation: 1818

Thanks @phuzi for the reference post in comment.

Based on the post, I've modified the answer as below and it works.

public static List<string> GetEnumMemberValues<T>() where T : struct, IConvertible
    {
        List<string> list = new List<string>();
        var members = typeof(T)
             .GetTypeInfo()
             .DeclaredMembers;
        foreach (var member in members)
        {
            var val = member?.GetCustomAttribute<EnumMemberAttribute>(false)?.Value;
            if (!string.IsNullOrEmpty(val))
                list.Add(val);
        }

        return list;
    }

Usage:

  1. Put the method in a class. I put it into EnumExtension.

  2. Call this method like this:

    var carList = EnumExtension.GetEnumMemberValues();

  3. The carList returns ["Rolls Royce", "Honda", "Mercedes Benz"] as expected.

Upvotes: 2

Related Questions