Reputation: 3491
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
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:
Upvotes: 6
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