我正在尝试按枚号排序列表,请参阅下文:
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
外部代码通过传递值来调用Add方法,例如:
animals.add(Fish)
animals.add(Horse)
animals.add(Cat)`
但是当调用GetAnimals
时,它应该返回Enum AnimalOrder
排序的列表。
因此,列表中应包含猫,马,鱼等顺序的动物
谢谢。答案 0 :(得分:1)
枚举在内部为每个值使用整数。如果您未明确设置它们,则会按照枚举中定义的顺序自动分配,从0
开始。
您应该能够将String值转换为枚举值,并从那里转换为整数。像(未经测试的)......
Public Function GetAnimals() as list(of Animal)
Return _animalList.OrderBy(function(x) Cint(DirectCast(Enum.Parse(GetType(AnimalOrder), x), AnimalOrder)))
End Sub
请注意,您将值称为类型Animal
,但在Q中没有定义。如果您需要访问属性以获取与Enum匹配的值,请说AnimalTypeString
...
Public Function GetAnimals() as list(of Animal)
Return _animalList.OrderBy(function(x) Cint(DirectCast(Enum.Parse(GetType(AnimalOrder), x.AnimalTypeString), AnimalOrder)))
End Sub
或者如果动物的AnimalType
属性直接指向枚举值(这是明智的),您可以跳过转换到枚举......
Public Function GetAnimals() as list(of Animal)
Return _animalList.OrderBy(function(x) Cint(X.AnimalType))
End Sub