Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vb.net custom attribute to an enum

I have this Enum:

<Flags()>
    Public Enum FilterEnum As Integer

    Green= 0
    Blue = 1
    Red = 2
    Yellow = 4

    End Enum

I would like to give to "Green" and "Yellow" some kind of an attribute so when i get the enum like this:

Dim enumItems = [Enum].GetValues(myEnum)

I will get only the Enum value of those who has that attribute, something like this:

Dim enumItems = [Enum].GetValues(myEnum).where(function(o) o.myAttribute)
like image 376
Offir Avatar asked Mar 24 '26 06:03

Offir


2 Answers

You can create a custom attribute for this way:

<AttributeUsage(AttributeTargets.Field)>
Public Class SomeAttribute
    Inherits System.Attribute
    Public Property SomeValue As String
End Class

Then create your enum and decorate fields with your attribute:

Public Enum MyEnum
    <Some(SomeValue:="Good One")>
    Member1 = 1
    <Some(SomeValue:="Bad One")>
    Member2 = 2
    <Some(SomeValue:="Good One")>
    Member3 = 3
End Enum

And using this query, get those you want, for example "Good One"s

'Indented to be more readable step by step
Dim result As List(Of MyEnum) = _
    GetType(MyEnum).GetFields() _
                   .Where(Function(field) _
                          field.GetCustomAttributes(True) _
                               .Cast(Of SomeAttribute) _
                               .Any(Function(attribute) attribute.SomeValue = "Good One")) _
                   .Select(Function(filtered) _
                           CType(filtered.GetValue(Nothing), MyEnum)) _
                   .ToList()

And the result will be:

enter image description here

like image 109
Reza Aghaei Avatar answered Mar 26 '26 18:03

Reza Aghaei


Maybe you can use System.ComponentModel.Description

<Flags()>
Public Enum FilterEnum As Integer
    <System.ComponentModel.Description("value_1")>_
    Green= 0
    <System.ComponentModel.Description("value_2")>_
    Blue = 1
    <System.ComponentModel.Description("value_3")>_
    Red = 2
    <System.ComponentModel.Description("value_4")>_
    Yellow = 4
End Enum

And then, check them so Get Enum from Description attribute

like image 27
Morcilla de Arroz Avatar answered Mar 26 '26 20:03

Morcilla de Arroz



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!