Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Getting all enums value by attribute

I have this following enum :

public enum KodEnum
{
    [EnumType(EnumType = "Task")]
    TaskTab,
    [EnumType(EnumType = "Task")]
    TaskReason,
    [EnumType(EnumType = "Action")]
    ActionTab,
    [EnumType(EnumType = "Action")]
    ActionReason
}

public class EnumTypeAttribute : Attribute
{
    public string EnumType { get; set; }
}

And I want to get a list of all the enums that have the EnumType of "Task".

How could I do that?

like image 471
Golan Kiviti Avatar asked Aug 06 '26 21:08

Golan Kiviti


1 Answers

Something like this should get you on the way...

var enumValues = (from member in typeof(KodEnum).GetFields()
                  let att = member.GetCustomAttributes(false)
                                  .OfType<EnumTypeAttribute>()
                                  .FirstOrDefault()
                  where att != null && att.EnumType == "Task"
                  select member.GetValue(null))
                 .Cast<KodEnum>()
                 .ToList();

If you want the int value, then just cast it:

var enumValues = (from member in typeof(KodEnum).GetFields()
                  let att = member.GetCustomAttributes(false)
                                  .OfType<EnumTypeAttribute>()
                                  .FirstOrDefault()
                  where att != null && att.EnumType == "Task"
                  select (int)member.GetValue(null))
                 .ToList();

And all-lambda solution:

        var enumValues = typeof(KodEnum)
            .GetFields()
            .Select(x => new 
                { 
                    att = x.GetCustomAttributes(false)
                             .OfType<EnumTypeAttribute>()
                             .FirstOrDefault(), 
                    member = x 
                })
            .Where(x => x.att != null && x.att.EnumType == "Task")
            .Select(x => (int)x.member.GetValue(null))
            .ToList();
like image 80
Tim Eeckhaut Avatar answered Aug 08 '26 09:08

Tim Eeckhaut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!