Sort List(of Object) by object properties

前端 未结 3 1288
南方客
南方客 2021-01-26 02:13

I\'m trying to achieve something where the answer is already given for. But it\'s in c# and I don\'t have any knowledge what-so-ever over c# so I\'m lo

3条回答
  •  感动是毒
    2021-01-26 02:40

    Another solution would be to implement the IComparable (see MSDN ref) interface. This interface is designed to sort your objects on a custom way :

    Public Class BomItem
        Implements IComparable
    
        Public Property ItemNumber As String
        Public Property Description As String
        Public Property Quantity As Double
        Public Property Material As String
        Public Property Certificate As String
    
        Public Function CompareTo(obj As Object) As Integer
             Dim bom = CType(obj, BomItem)
    
             If Not bom Is Nothing then
                 Return Me.ItemNumber.CompareTo(bom.ItemNumber)
             Else
                 Throw New ArgumentException("Object is not a BomItem")
             End If
    End Class
    

    and you can sort the list this way :

    Dim myList As New List(Of BomItem)
    
    'Code to add your BomItems
    
    myList.Sort()
    

    This will actually sort your list, it does not create a new list.

提交回复
热议问题