Offir
Offir

Reputation: 3491

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)

Upvotes: 3

Views: 3130

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125197

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

Upvotes: 6

Morcilla de Arroz
Morcilla de Arroz

Reputation: 2182

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

Upvotes: 1

Related Questions