Reputation: 493
I'm trying to order a list by enum please see below:
Public Class AnimalsToProcess
Implements ICloneable
Enum AnimalOrder
Dog
Cat
Horse
Fish
End Enum
Public Property _animalList As List(Of Animal)
Public Sub New()
End Sub
Function Clone() As AnimalsToProcess
End Function
Private Function ICloneable_Clone() As Object Implements ICloneable.Clone
Return Clone()
End Function
Public Sub Add(animalToAdd As Animal)
_animalList.Add(animalToAdd)
End Sub
Public Sub GetAnimals() as list(of Animal)
_animalList() 'this should be an ordered BY AnimalOrder Enum
End Sub
End Class
The Add method is called by the external code by passing a value , eg:
animals.add(Fish)
animals.add(Horse)
animals.add(Cat)`
but when the GetAnimals
is called it should return a list ordered by theEnum AnimalOrder
.
hence then list should contain the follwing animals in this order cat,horse,fish
thank you.
Upvotes: 1
Views: 92
Reputation: 26766
Enums use integers internally for each value. If you don't set them explicitly, they're auto-assigned in the order defined in the enum, starting with 0
.
You should be able to cast your String value to your enum and from there to an integer. Something like (untested)..
Public Function GetAnimals() as list(of Animal)
Return _animalList.OrderBy(function(x) Cint(DirectCast(Enum.Parse(GetType(AnimalOrder), x), AnimalOrder)))
End Sub
Note that you're referring to the value as type Animal
but don't have a definition of that in your Q. If you need to access a property to get the value to match to the Enum, say AnimalTypeString
...
Public Function GetAnimals() as list(of Animal)
Return _animalList.OrderBy(function(x) Cint(DirectCast(Enum.Parse(GetType(AnimalOrder), x.AnimalTypeString), AnimalOrder)))
End Sub
OR If the AnimalType
property on your animal points directly at the enum value (Which would be sensible) you can skip out the conversion to enum...
Public Function GetAnimals() as list(of Animal)
Return _animalList.OrderBy(function(x) Cint(X.AnimalType))
End Sub
Upvotes: 1